react中ref的三种使用方法
一:字符串类型refs(最简单但官方不推荐使用)
直接给文本节点绑定ref=“_name”,然后使用this.refs._name.xxx 获取
此时所有的ref都绑定在实例对象的refs属性中
<input ref="inp1" placeholder="请输入内容"></input>
{/* ref的字符串方法 */}
<button onClick={()=>{alert(this.refs.inp1.value)}}>点击弹出左侧内容</button>
二:使用回调函数refs
用回调函数绑定ref,在对应文本节点上写入 ref={(currentNode)=>{this._name=currentNode}}
对应参数currentNode其实就是该文本节点,将该文本节点取一个别名_name
挂在实例上,可以直接this. ,注意,这里的ref不存在于实例的refs属性中
{/* ref的回调函数方法 */}
<input ref={(currentNode)=>{this.inp1=currentNode}} placeholder="请输入内容"></input>
<button onClick={()=>{alert(this.inp1.value)}}>点击弹出左侧内容</button>
三:使用React.createRef()
首先声明一个_name=React.createRef(),然后就可以直接使用
该ref挂在实例对象上,也是一个对象,获取时用this._name.current.xxx获取
注意:该_name 是每个文本节点独有的,也就是说要绑定多个ref时需要创建多个对象
myRef = React.createRef()
render() {
return <div>
{/* ref的回调函数方法 */}
<input ref={this.myRef} placeholder="请输入内容"></input>
<button onClick={()=>{console.log(this.myRef.current.value)}}>点击弹出左侧内容</button>
</div>
}