React Component Specs and Lifecycle (组件和生命周期)
组件规格
当创建一个React组件,并调用 React.createClass(),你需要提供一些Object对象,例如必须的render,还有其他一些可选的Object对象。
render
这个函数对象必须存在,且一定存在返回值。
render: function () {
return (<h2>Hello, World!</h2>);
}
官方规范说明这个方法一定要pure(干净),保证职责单一,所有数据通过props和state来。利于组件的复用和维护。写React一定要约束好各种规范!
返回值是 ReactElement
getInitialState
object getInitialState()
在组件装载前会调用一次,函数的返回值对象,可以在this.state查询和使用。
getDefaultProps
object getDefaultProps()
在组件装载前会调用一次,函数的返回值对象,可以在this.props查询和使用。
和state不同的是,props在每个实例里都可以访问到,只会拷贝一次,而this.state是实例独享的。
propTypes
object propTypes
可以约束检测你的参数的,发现不匹配就会console.wran()来提示错误,但是不会报错不执行。
mixins(ES6已经不支持了)
array mixins
支持多个组件之间共享公用的方法,共享使用共同的变量和方法。
statics
object statics
给你的组件增加静态的方法。
var MyComponent = React.createClass({
statics: {
customMethod: function(foo) {
return foo === 'bar';
}
},
render: function() {
}
});
MyComponent.customMethod('bar'); // true
displayName
string displayName
用于debug时候的定位。
生命周期方法
实例化
当首次使用组件类时,下面这些方法依次被调用。
-
getDefaultProps
-
getInitialState
-
componentWillMount
-
render
-
componentDidMount
当组件类再次被调用时getDefaultProps方法不会被调用。
存在期
当实例已经生成,修改属性时,以下方法会依次被调用
-
componentWillReceiveProps
-
shouldComponentUpdate
-
componentWillUpdate
-
render
-
componentDidUpdate

浙公网安备 33010602011771号