react获取ref的几种形式

react 获取ref的几种形式

定义
constructor(props) {
  super(props);
  this.state = {};
  this.textInput = React.createRef(); //看这里
}

绑定
render() {
  return (
    <div>
      <p>测试原生事件与合成事件的区别</p>
      <div>
        <button ref={this.textInput} //看这里 className="button" onClick={this.onReactClick}>
          点击
        </button>
      </div>
    </div>
  );
}

使用
this.textInput.current.addEventListener('click', this.onDomClick, false);
绑定
render() {
  return (
    <div>
      <p>测试原生事件与合成事件的区别</p>
      <div>
        <button ref="textInput"  //看这里 className="button" onClick={this.onReactClick}>
          点击
        </button>
      </div>
    </div>
  );
}

使用
this.refs.textInput.addEventListener('click', this.onDomClick, false);
绑定
render() {
  return (
    <div>
      <p>测试原生事件与合成事件的区别</p>
      <div>
        <button ref="textInput" className="button" onClick={this.onReactClick}>
          点击
        </button>
      </div>
    </div>
  );
}

使用
const parentDom = ReactDOM.findDOMNode(this.refs.textInput); //看这里
parentDom.addEventListener('click', this.onDomClick, false);

ReactDOM.findDOMNode(this)  //可以直接获取到当前组件根节点

猜你喜欢

转载自www.cnblogs.com/panrui1994/p/11829638.html