一、在react中,如果我们想获取元素节点,那么refs就能帮你搞定这个问题了,话不多说上代码
//字符串形式的ref
class Demo extends React.Component{
getInputValue = () =>{
const data = this.$refs.input1.value
}
render(){
return (
<div>
<input ref="input1" type="text"/>
<button onClick={this.getInputValue}></button>
</div>
)
}
}
上面我们使用的是最简单的一种ref使用方法,就是使用一个字符串名称,然后通过调用refs来获取对应的节点,但是官方文档说这种用法以后会被弃用,那么我们就放弃它吧,改用其他写法。
二、refs之回调函数写法
class Demo extends React.Component{
getInputValue = () =>{
const {input1} = this
}
render(){
return (
<div>
<input ref={c => this.input1 = c} type="text"/>
<button onClick={this.getInputValue}></button>
</div>
)
}
}
这种回调函数的写法看着有点懵逼,字符串写法不是更简单么,我也觉得,但是人家说字符串写法有效率问题,没辙,只能改。回调函数写法呢,主要是在实例定义一个input1属性,然后回调函数会返回一个参数c,接着把这个c赋值给input1,完事了。
三、refs之createRef Api的写法
class Demo extends React.Component{
input1 = React.createRef();
getInputValue = () =>{
const {input1} = this
}
render(){
return (
<div>
<input ref={this.input1} type="text"/>
<button onClick={this.getInputValue}></button>
</div>
)
}
}
好了,第三种写法就是使用官方提供的API createRef()来写,首先在实例里定义一个input1 并使用createRef来初始话它,接着直接在元素那里直接使用接完事了。