React State(state)


React treats components as state machines. By interacting with the user, different states are achieved, and then the UI is rendered to keep the user interface and data consistent.

In React, you only need to update the state of the component, and then re-render the user interface based on the new state (without manipulating the DOM).

The LikeButton component is created in the following example. The getInitialState method is used to define the initial state, which is an object. This object can be read through the this.state property. When the user clicks on the component, causing the state to change, the this.setState method modifies the state value. After each modification, the this.render method is automatically called to render the component again.

Instance

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>php中文网 React 实例</title>
    <script src="http://static.php.cn/assets/react/react-0.14.7/build/react.min.js"></script>
    <script src="http://static.php.cn/assets/react/react-0.14.7/build/react-dom.min.js"></script>
    <script src="http://static.php.cn/assets/react/browser.min.js"></script>
  </head>
  <body>
    <div id="example"></div>
    <script type="text/babel">
      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 ? '喜欢' : '不喜欢';
          return (
            <p onClick={this.handleClick}>
              你<b>{text}</b>我。点我切换状态。
            </p>
          );
        }
      });

      React.render(
        <LikeButton />,
        document.getElementById('example')
      );
    </script>
  </body>
</html>

Run instance»

Click the "Run instance" button to view the online instance