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