Latest web development tutorials

React State (state)

React to the component as a state machine (State Machines). Through interaction with the user, to achieve different states, then render the UI, so that the user interface and data consistency.

React years, simply update the state assembly, and then re-render the user interface based on the new state (not to operate DOM).

The following example createsLikeButton components, getInitialState method used to define the initial state, that is, a object that can be read by this.state property.When the user clicks on the component, resulting in a state change, this.setState method to modify the status value after each modification automatically call this.render renders the component again.

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')
);

try it"