0%

730_React_createref容器

<script type="text/babel">
      //ref:相当于id,用于获取元素标签
      class Demo extends React.Component {
        //React.createRef()调用可以返回一个容器,该容器可以存储ref所标识的节点,属于专人专用的
        myRef = React.createRef();
        myRef2 = React.createRef();
        showData = () => {
          console.log(this);
          alert(this.myRef.current.value);
        };
        showData2 = () => {
          console.log(this);
          alert(this.myRef2.current.value);
        };
        render() {
          return (
            <div>
              <input
                ref={this.myRef}
                type="text"
                placeholder="点击按钮提示数据"
              />
              <button onClick={this.showData}>点击我提示左侧数据</button>
              <input
                onBlur={this.showData2}
                //这里的ref直接给实例化对象添加了input2,c的值就是input这个标签节点
                ref={this.myRef2}
                type="text"
                placeholder="失去焦点提示数据"
              />
            </div>
          );
        }
      }

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