1)定义组件(2种方式)
/*方式1: 工厂函数组件(简单组件)*/
function MyComponent () {
return <h2>工厂函数组件(简单组件)</h2>
}
/*方式2: ES6类组件(复杂组件)*/
class MyComponent2 extends React.Component {
render () {
console.log(this) // MyComponent2的实例对象
return <h2>ES6类组件(复杂组件)</h2>
}
}
2)渲染组件标签
ReactDOM.render(<MyComponent />, document.getElementById('example1'))
2.2.2. 编码操作
1)初始化状态:
constructor (props) {
super(props)
this.state = {
stateProp1 : value1,
stateProp2 : value2
}
}
2)读取某个状态值
this.state.statePropertyName
3)更新状态---->组件界面更新
this.setState({
stateProp1 : value1,
stateProp2 : value2
})
每个组件对象都会有props(properties的简写)属性 组件标签的所有属性都保存在props中
通过标签属性从组件外向组件内传递变化的数据 注意: 组件内部不要修改props数据
1)内部读取某个属性值
this.props.propertyName
2)对props中的属性值进行类型限制和必要性限制
Person.propTypes = {
name: React.PropTypes.string.isRequired,
age: React.PropTypes.number.isRequired
}
3)扩展属性: 将对象的所有属性通过props传递
<Person {...person}/>
4)默认属性值
Person.defaultProps = {
name: 'Mary'
}
5)组件类的构造函数
constructor (props) {
super(props)
console.log(props) // 查看所有属性
}
问题: 请区别一下组件的props和state属性
<input onFocus={this.handleClick}/>
handleFocus(event) {
event.target //返回input对象
}
生命周期流程:
npm install -g create-react-app create-react-app hello-react cd hello-react npm start
ReactNews |--node_modules---第三方依赖模块文件夹 |--public |-- index.html-----------------主页面 |--scripts |-- build.js-------------------build打包引用配置 |-- start.js-------------------start运行引用配置 |--src------------源码文件夹 |--components-----------------react组件 |--index.js-------------------应用入口js |--.gitignore------git版本管制忽略的配置 |--package.json----应用包配置文件 |--README.md-------应用描述说明的readme文件
https://github.com/axios/axios
1)GET请求
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
2)POST请求
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
1)https://github.github.io/fetch/
2)https://segmentfault.com/a/1190000003810652
1)GET请求
fetch(url).then(function(response) {
return response.json()
}).then(function(data) {
console.log(data)
}).catch(function(e) {
console.log(e)
});
2)POST请求
fetch(url, {
method: "POST",
body: JSON.stringify(data),
}).then(function(data) {
console.log(data)
}).catch(function(e) {
console.log(e)
})