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
}} />

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM