React State state

Article directory


React State state

insert image description here

React treats components as state machines. Through the interaction with the user, achieve different states, and then render the UI, so that the user interface and data are consistent.

In React, you only need to update the state of the component, and then re-render the user interface according to the new state (do not manipulate the DOM).

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

React instance

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>React 实例</title>
<script src="http://cdn.bootcss.com/react/15.4.2/react.min.js"></script>
<script src="http://cdn.bootcss.com/react/15.4.2/react-dom.min.js"></script>
<script src="http://cdn.bootcss.com/babel-standalone/6.22.1/babel.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>
          );
        }
      });

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

running result:
insert image description here

Guess you like

Origin blog.csdn.net/m0_62617719/article/details/130601176