React从0开始(十):React Ref与useRef

998 阅读2分钟

这是我参与11月更文挑战的第11天,活动详情查看:2021最后一次更文挑战

我们今天来学习一下ReactRef以及React Hooks中的useRef

一、RefuseRef的区别

首先我们先来了解一下Ref对象:Ref对象是我们通过React.createRef或利用React Hooks——useRef生成的一个对象,一个标准的Ref对象往往是以下形式:

{
    current:null
}

在生成Ref对象时,往往有两种方法,在类组件中,我们往往使用React.createRef来生成Ref对象。而useRef通常用于函数组件Ref对象的生成,这便是React.createuseReact在使用层面上的一个区别。

简单来说:

  • React.createRef能够在类组件函数组件中使用
  • useRef仅能够在函数组件中使用

究其原因:

函数组件会随着函数的不断执行而刷新,React.createRef所得到的的Ref对象因重复初始化而无法得到保存,而使用类组件对生命周期进行了分离,不受影响

二、RefuseRef都能拿来做什么

  • 可以获取DOM元素以及DOM元素的属性
  • 获取组件实例以及组件的方法

注:如果Ref获取的是DOM元素,则getref.currentDOM内容。如果获取的是子组件,则getref.current子组件实例

三、RefuseRef的使用

Ref的使用有四种方法:字符串、回调函数、React.createRefuseRef

我们一个个来看:

1、字符串(不推荐使用)

创建、使用方式:

  1. 在标签内通过ref="Target"定义Ref
  2. 通过this.refs.Target访问获取的DOM组件实例
import React from 'react';
class DoRef extend React.Component {
    render() {
        return (
            <input  ref={"inputText"} />
        )
    }
    getRef() {
        console.log(this.refs.inputText)
    }
}

2、回调函数

创建、使用方式:

  1. 在标签内通过ref={ (ele) => { this.Target = ele } }定义Ref
  2. 通过this.Target访问获取的DOM组件实例
import React from 'react';
class DoRef extend React.Component {
    render() {
        return (
            <input  ref={ (input)=>{ this.inputText = input } } />
        )
    }
    getRef() {
        console.log(this.inputText)
    }
}

3、React.createRef

创建、使用方式:

  1. 在函数组件内调用const Target = React.creatRef(null)
  2. 通过Target.current访问获取的DOM组件实例
import React from 'react';
class DoRef extend React.Component {
    constructor(props) {
        super(props);
        this.inputText = React.creatRef(null);
    }
    componentDidMount() { 
        this.inputText && this.inputText.current.focus(); 
    }
    render() {
        return (
            <input  ref={inputText} />
        )
    }
    getRef() {
        console.log(this.inputText.current);
    }
}

4、useRef

创建、使用方式:

  1. 导入useRef钩子
  2. 在函数组件内调用const Target = useRef(null)
  3. 通过Target.current访问获取的DOM组件实例

useRef所返回的Ref对象在组件中整个生命周期内保持不变,因此能够用于函数组件

import React,{useRef} from 'react';
const Example = () => {
    const inputText = useRef(null);
    return (
        <input  ref={inputText.current} />
    )
}