第一種形式
定義 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 }} />