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)  //可以直接获取到当前组件根节点
第四种形式
ref回调形式
class SearchBar extends Component {
   constructor(props) {
      super(props);
      this.txtSearch = null;
      this.setInputSearchRef = e => {
         this.txtSearch = e; //看这里
      }
   }
   render() {
      return (
         <input
            ref={this.setInputSearchRef} /> //看这里
      );
   }
}
第五种形式
内联样式
<input ref={(userName) => {
 this.userName = userName
}} />
不忘初心,不负梦想
原文地址:https://www.cnblogs.com/panrui1994/p/11829638.html