React框架有一個特性,當React檢測到頁面內容有變化是,它會自動刷新頁面,並且自動更新頁面中需要更新的部分。但是React並不會把更新的內容掛在真是的DOM上,因此我們單單對頁面數據或者組件改動是,並不會看到頁面有任何變化。React提供了組件的一個私有的,其他任何組件沒有權限改變的屬性:state(狀態)。我們可以通過ES6的類定義一個組件: (訪問上一個組件的狀態可用prevState獲取)
class Clock extends React.Component{
constructor(props) {
super(props);
this.state = {date: new Date()}
}
};
在組件的構造函數中,我們定義了一個組件狀態的一個屬性:date,當組件內容需要變化是,我們改變state的對應的值就可以了。這里我們每過一秒更新一次顯示的時間,那么我們就每過一秒跟新一次this.state的date的值。代碼如下:
class Clock extends React.Component{
constructor(props) {
super(props);
this.state = {date: new Date()}
}
componentDidMount() { //組件渲染完成,要掛載到頁面前執行的代碼
this.timer = setInterval(
() => this.trick(),
1000
);
}
componentWillUnmount() { //組件從頁面卸載前執行的方法
clearInterval(this.timer);
}
trick() {
this.setState({date: new Date()}); //改變組件的狀態
}
render() {
return (
<div>
<h1>Hello World!</h1>
<h2>{this.state.date.toLocaleTimeString()}</h2>
</div>
);
}
};
ReactDOM.render(
<Clock/>,
document.getElementById('main')
);
這樣,頁面會顯示一個精確到秒的電子表啦!