0%

730_React_ref回调函数形式执行次数

<script type="text/babel">
      //ref:相当于id,用于货物元素标签
      class Demo extends React.Component {
        state = { isHot: true };
        showData = () => {
          console.log(this);
          alert(this.input1.value);
        };
        showData2 = () => {
          console.log(this);
          alert(this.input2.value);
        };
        changeWeather = () => {
          this.setState({ isHot: !this.state.isHot });
        };
        render() {
          const { isHot } = this.state;
          return (
            <div>
              <h2 onClick={this.changeWeather}>
                今天天气很{isHot ? "炎热" : "凉爽"}
              </h2>
              {/*如果把函数写成这种内联形式的,第二次渲染更新页面的时候先会传递一个null清空,然后才会传递节点
                1、null
                2、<input点击按钮提示数据"/>*/}
              <input
                ref={(c) => {
                  this.input1 = c;
                  console.log(c);
                }}
                type="text"
                placeholder="点击按钮提示数据"
              />
              <button onClick={this.showData}>点击我提示左侧数据</button>

              {/*<input
                onBlur={this.showData2}
                //这里的ref直接给实例化对象添加了input2,c的值就是input这个标签节点
                ref={(c) => {
                  this.input2 = c;
                }}
                type="text"
                placeholder="失去焦点提示数据"
            />*/}
            </div>
          );
        }
      }

      //渲染
      //这里面的{...p},相当于展开name: "Tom", sex: "男", age: "18"
      ReactDOM.render(<Demo />, document.getElementById("test"));
    </script>