类式组件使用Ref

1.字符串形式的ref

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Demo extends React.Component{
showData = () => {
const {input1} = this.refs
alert(input1.value)
}

render(){
return (
<div>
<input ref="input1" type="text" placeholder = "点击按钮提示数据">
<button onClick={this.showData}>点我提示数据</button>
</div>
)
}
}

过时API: String类型的Refs,在官方文档中,不建议使用它,因为string类型的refs存在一些问题,在将来会被移除

2.回调形式的Ref

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Demo extends React.Component{
showData = () => {
const {input1} = this
alert(input1.value)
}

render(){
return (
<div>
<input ref= {current => this.input1 = current} type="text" placeholder = "点击按钮提示数据">
<button onClick={this.showData}>点我提示数据</button>
</div>
)
}
}

current 指的是ref当前所在的元素,例如

如果ref回调是以内联函数的形式定义的,在更新的过程中,会被执行两次,第一次传入参数为null,第二次为当前ref,但是没有太大影响

3.使用createRef API

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Demo extends React.Component{
myRef = React.createRef()

showData = ()=>{
alert(this.myRef.current.value)
}
render(){
return (
<div>
<input ref= {this.myRef} type="text" placeholder = "点击按钮提示数据">
<button onClick={this.showData}>点我提示数据</button>
</div>
)
}
}

createRef调用后可以返回一个容器,该容器可以存储被ref标识的容器,且只能存一个

Hook useRef

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function Demo(){
const myRef = React.useRef()

function showData(){
alert(myRef.current.value)
}

return (
<div>
<input ref= {myRef} type="text" placeholder = "点击按钮提示数据">
<button onClick={this.showData}>点我提示数据</button>
</div>
)
}