
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
}} />相关学习推荐:react视频教程
以上就是react怎样取得ref的值的详细内容,更多请关注易知道|edz.cc其它相关文章!














