react 中ref的3种用法


1.字符串
通过 this.refs.test 来引用真实dom的节点
dom 节点上使用

<input type ="text" ref="test"/> 

2.回调函数
回调函数就是在dom节点或组件上挂载函数,函数的入参是dom节点或组件实例,达到的效果与字符串形式是一样的,
都是获取其引用。

<input type="text" ref={(input)=>{this.textInput=input}} 

3.React.createRef()
在React 16.3版本后,使用此方法来创建ref。将其赋值给一个变量,通过ref挂载在dom节点或组件上,该ref的current属性将能拿到dom节点或组件的实例

class Counter extends Component {
constructor() {
super()
this.state ={sum:0,number:0}
this.myRef = React.createRef();
}
change = () =>{
this.setState({...this.state,sum: Number(this.textInput.value) + Number(this.myRef.current.value)})
}
componentDidMount(){
console.log(this.myRef.current.value);
}
render() {
return (
<div onChange ={this.change} >
<input type="text" ref={(input)=>{this.textInput=input}} />+ 
<input type ="text" ref={this.myRef} /> = {this.state.sum}
</div>

)
}
}
原文地址:https://www.cnblogs.com/ll15888/p/13271790.html