2. React 学习
- 生命周期
生命周期 | 调用次数 | 能否使用setState() | 参数 | 时机、作用 |
---|---|---|---|---|
getDefaultProps | 1 | no | 组件加载前获取组件的props | |
getInitialState | 1 | no | 初始化组件state | |
componentWillMount | 1 | yes | 组件第一次绘制前初始化或设置组件状态 | |
render | >=1 | no | 绘制组件 | |
componentDidMount | 1 | yes | 第一次绘制后调用,从这个函数开始可以和js交互 | |
componentWillReceiveProps | >=0 | yes | nextProps | 收到新的props时调用 |
shouldComponentUpdate | >=0 | no | nextProps、nextState | props或state改变时调用 当结果是true时调用下个函数 |
componentWillUpdate | >=0 | no | nextProps、nextState | shouldComponentUpdate结果为true时调用,把nextProps nextState设置到this.props this.state 之后会调用render |
componentDidUpdate | >=0 | no | prevProps、prevState | render调用后会调用本函数来通知 |
componentWillUnmount | 1 | no | 当组件要被从界面移除的时候,会调用本函数,可以调用一些相关的清理工作,如取消计时器等 |
* jsx基本语法规则
遇到HTML标签(以<开头)用HTML解析;遇到代码块(以{开头)用js规则解析。
jsx可以插入数组,会将数组内容展开
- 组件
React 允许将代码封装成组件(component),然后像插入普通 HTML 标签一样,在网页中插入这个组件。
React.createClass
方法就用于生成一个组件类
var Hello = React.createClass({
render: function () {
return <h1>Hello World</h1>;
}
});
Hello
现在就是一个组件类,在模板插入<Hello />
时会自动生成一个实例。组件的render
方法用于输出组件
++组件类首字母要大写 不然会报错++
++组件类只能有一个顶级标签,不然会报错,如果包含多个,可以用div包起来++
添加组件属性要注意++class 写成className,for写成htmlFor++
React.Children.map
React.Children.forEach
React.Children.count
React.Children.only
这四个工具函数用于处理this.props.children,都以
this.props.children
作为第一参数,其中前两个有第二参数
var tagList = React.createClass({
render: function () {
return (
<ol>
{
React.Children.map(this.props.children, function (child) {
return <li>{child}</li>;
})
}
</ol>
);
}
});
map 和 forEach类似,区别是map有返回值forEach没有,当this.props.children是null或undefined时,会返回null或undefined
- PropTypes
PropTypes用来验证组件的props是否符合要求
var MyTitle = React.createClass({
propTypes: {
title: React.PropTypes.string.isRequired,
},
render: function () {
return <h1>Hello World</h1>;
}
});
可以限制title的数据类型,以及这个属性是必须的。