一個組件類必須由調用 React.createClass
建立,而且提供一個 render
方法以及其餘可選的生命週期函數、組件相關的事件或方法定義。html
一個簡單的例子:react
var LikeButton = React.createClass({ getInitialState: function() { return {liked: false}; }, handleClick: function(event) { this.setState({liked: !this.state.liked}); }, render: function() { var text = this.state.liked ? 'like' : 'haven\'t liked'; return ( <p onClick={this.handleClick}> You {text} this. Click to toggle. </p> ); } }); React.render( <LikeButton />, document.getElementById('example') );
getInitialState
初始化 this.state
的值,只在組件裝載以前調用一次。git
getDefaultProps
只在組件建立時調用一次並緩存返回的對象(即在 React.createClass
以後就會調用)。github
由於這個方法在實例初始化以前調用,因此在這個方法裏面不能依賴 this
獲取到這個組件的實例。web
在組件裝載以後,這個方法緩存的結果會用來保證訪問 this.props
的屬性時,當這個屬性沒有在父組件中傳入(在這個組件的 JSX 屬性裏設置),也老是有值的。api
render
必須緩存
組裝生成這個組件的 HTML 結構(使用原生 HTML 標籤或者子組件),也能夠返回 null
或者 false
,這時候 React 會將組件生成一個 <noscript>
標籤,而且 this.getDOMNode()
會返回 null
。函數
componentWillMount
this
只會在裝載以前調用一次,在 render
以前調用,你能夠在這個方法裏面調用 setState
改變狀態,而且不會致使額外調用一次 render
spa
componentDidMount
只會在裝載完成以後調用一次,在 render
以後調用,從這裏開始能夠經過 this.getDOMNode()
獲取到組件的 DOM 節點。
這些方法不會在首次 render
組件的週期調用
componentWillReceiveProps
shouldComponentUpdate
componentWillUpdate
componentDidUpdate
componentWillUnmount
更多關於組件相關的方法說明,參見: