React类组件创建ref的三种方式

4,312 阅读1分钟

前言

在react类组件中ref的创建有三种方法,他们分别是①字面量的创建②回调函数的创建使用③createRef创建。在使用字面量创建使用比较常见,但是官方不推荐,甚至后面可能被弃用。下面让我来一一介绍。

字面量创建

用字面量的方式创建比较简单,只需要如下代码

render(){
    return (
        <h1 ref = "h1"></h1>
        <input ref = "input1" />
    )
}

因为在实例身上有一个refs属性,即this.refs。所以采用用ref标识的h1input1,会被以{key:value}的形式收集在this.refs中。使用的时候用this.refs.h1即可拿到render中的h1元素。

回调函数创建(推荐)

render(){
    return (
        <input ref = {c => this.input1 = c} />
    )
}

这种方式的意思是:参数 c 即是当前的dom元素。并且把它放在了实例上。在使用时可以从this中解构出变量使用,但是回调函数形式存在一丢丢问题,在官网有说明,也就是在render再次更新时,回调函数会被调用两次,第一次拿到的是 dom元素是null,第二次才会拿到dom元素。解决这个问题,可以定义一个回调函数,将回调交给react去执行,如下:

createRef = (c) => {
    //此参数中就是所需要的元素
}
render(){
    return (
        <input ref = {this.createRef} />
    )
}

createRef创建

class Ref extends React.Component {
    myRef = React.createRef()
    myRef2 = React.createRef()
}
render() {
    return (
        <input ref = {this.myRef} />
        <input ref = {this.myRef2} />
    )
}

createRef()调用后返回一个容器,其中就包含了被ref所标识的节点。myref在子类的实例对象上,所以在render中的return中可以用this.myref标识。在方法中可以用this.myref.current拿到dom元素。