在使用React编写代码时,难免会遇到需要获取到真实DOM节点的时候,那么在React中我们怎么去获取呢?以下总结了几种方法:
1. 通过在标签中添加ref属性(react官方已弃用)
class Index extends Component {
onClick(event){
const inputDom = this.refs.submit;
console.log(inputDom);
}
render(){
return (
<div>
<input ref='submit' type='button' value='getDom' onClick={this.onClick.bind(this)}/>
</div>
)
}
}
2. 在标签中写入一个匿名函数
class Input extends Component {
componentDidMount() {
console.log(this.textInput);
}
render() {
return (
<input
type="text"
ref={input => this.textInput = input}
/>
);
}
3. 在标签中加入一个回调函数
class CustomTextInput extends Component {
constructor(props) {
super(props);
this.textInput = React.createRef();
}
render() {
return (
<input
type="text"
ref={this.textInput}
/>
);
}
参考链接:https://blog.youkuaiyun.com/liangklfang/article/details/72858295