0%

729_React_state天气案例

<script type="text/babel">
      class Weather extends React.Component {
        constructor(props) {
          super(props);
          //1、更改原型上面的handleClick函数并将this改为实例化对象
          //2、将这个函数赋值给一个新的函数handleClick ,并把他放在实例化对象自己身上
          this.handleClick = this.handleClick.bind(this);
          this.state = { ishot: true };
        }

        render() {
          // 这里面的this指向的是实例化对象
          //console.log(this);
          let content;
          if (this.state.ishot) {
            content = "炎热";
          } else {
            content = "凉爽";
          }
          return <h1 onClick={this.handleClick}>今天天气很{content}</h1>;
        }

        handleClick() {
          //谁调用指向谁
          //这里面由于onClick={this.handleClick},
          //handleClick是作为onClick的回调,而不是通过实例化对象直接调用的,且类里面的方法开启了严格模式,所以this为undefined
          console.log(this);
          console.log(this.state.ishot);
          //state的状态不能直接修改,要用setState
          const { ishot } = this.state;
          this.setState({ ishot: !ishot });
        }
      }

      //渲染
      ReactDOM.render(<Weather />, document.getElementById("test"));
    </script>