React中,經過改變組件的狀態來改變頁面的內容

  React框架有一個特性,當React檢測到頁面內容有變化是,它會自動刷新頁面,而且自動更新頁面中須要更新的部分。可是React並不會把更新的內容掛在真是的DOM上,所以咱們單單對頁面數據或者組件改動是,並不會看到頁面有任何變化。React提供了組件的一個私有的,其餘任何組件沒有權限改變的屬性:state(狀態)。咱們能夠經過ES6的類定義一個組件: (訪問上一個組件的狀態可用prevState獲取)框架

  

class Clock extends React.Component{
  constructor(props) {
    super(props);
    this.state = {date: new Date()}
  }函數

};this

 

在組件的構造函數中,咱們定義了一個組件狀態的一個屬性:date,當組件內容須要變化是,咱們改變state的對應的值就能夠了。這裏咱們每過一秒更新一次顯示的時間,那麼咱們就每過一秒跟新一次this.state的date的值。代碼以下:spa

  

class Clock extends React.Component{
  constructor(props) {
    super(props);
    this.state = {date: new Date()}
  }component

  componentDidMount() { //組件渲染完成,要掛載到頁面前執行的代碼
    this.timer = setInterval(
      () => this.trick(),
      1000
    );
  }get

  componentWillUnmount() { //組件從頁面卸載前執行的方法
    clearInterval(this.timer);
  }class

  trick() {
    this.setState({date: new Date()}); //改變組件的狀態
  }渲染

  render() {
    return (
      <div>
        <h1>Hello World!</h1>
        <h2>{this.state.date.toLocaleTimeString()}</h2>
      </div>
    );
  }
};date

ReactDOM.render(
  <Clock/>,
  document.getElementById('main')
);

這樣,頁面會顯示一個精確到秒的電子錶啦!權限

相關文章
相關標籤/搜索