var Card=React.createClass({
getDefaultProps:function(){
return {
title:'頭部',
content:'內(nèi)容區(qū)'
}
},
render:function(){
return (
<div><p>{this.props.title}</p><p>{this.props.content}</p></div>
)
}
});
ReactDOM.render(
<Card/>,
document.body
);
var MyButton=React.createClass({
getInitialState:function(){
return {isFriend:false}
},
handleClick:function(event){
this.setState({isFriend:!this.state.isFriend});
},
render:function(){
var friend=this.state.isFriend ? '添加好友' : '刪除好友';
return (
<div>
<button onClick={this.handleClick}>{friend}</button>
</div>
);
}
});
ReactDOM.render(
<MyButton/>,
document.body
);
componentWillMount
該方法會在完成渲染之前被調(diào)用,這也是在render方法調(diào)用前可以修改state的最后一次機會。
render
該方法會創(chuàng)建一個虛擬DOM,用來表示組件的輸出。對于一個組件來說,render是唯一一個必需的方法,并且有特定的規(guī)則。render方法需要滿足下面幾點:
componentDidMount
在render方法成功調(diào)用并且真實的DOM已經(jīng)被渲染,你可以在這個方法內(nèi)部通過 this.getDOMNode() 方法訪問到它。
2.存在期
這個階段,組件已經(jīng)渲染好并且用戶可以與它進行交互。通常是通過一次鼠標點擊、手指點按或鍵盤事件來觸發(fā)一個事件處理器。
componentWillReceiveProps
在任何時刻,組件的props都可以通過父輩組件來更改。這時,這個方法會被調(diào)用,我們也將獲得更改props對象及更新state的機會。
shouldComponentUpdate
如果你確定某個組件或其任何子組件不需要渲染新的props或state,可以通過在這個方法里通過返回 false 來阻止組件的重新渲染,返回 false 則不會執(zhí)行 render 以及后面的 componentWillUpdate,componentDidUpdate 方法。
該方法是非必需的,并且大多數(shù)情況下沒必要在開發(fā)中使用。
componentWillUpdate
和componentWillMount方法類似,組件會在接收到新的props或state進行渲染之前,調(diào)用此方法。
注意:不可以在該方法中更新state或props,而應該借助 componentWillReceiveProps 方法在運行時更新state。
componentDidUpdate
這個方法和 componentDidMount 類似,在組件重新被渲染之后,此方法會被調(diào)用??梢栽谶@里訪問并修改 DOM。
3.銷毀&清理期
在此階段,只有一個方法會被調(diào)用,完成所有的清理和銷毀工作。
componentWillUnmount
每當React使用完一個組件,這個組件必須從 DOM 中卸載后被銷毀,此時 componentWillUnmout 會被執(zhí)行,完成所有的清理和銷毀工作,在 conponentDidMount 中添加的任務都需要再該方法中撤銷,如創(chuàng)建的定時器或事件監(jiān)聽器。
總結(jié)
React生命周期方法提供了精心設計的鉤子函數(shù),會伴隨組件的整個生命周期。和狀態(tài)機類型,每個組件都被設計成了能夠在整個生命周期中輸出穩(wěn)定、語義化的標簽。
更多建議: