这是我参与11月更文挑战的第11天,活动详情查看:2021最后一次更文挑战
我们今天来学习一下React的Ref以及React Hooks中的useRef
一、Ref与useRef的区别
首先我们先来了解一下Ref对象:Ref对象是我们通过React.createRef或利用React Hooks——useRef生成的一个对象,一个标准的Ref对象往往是以下形式:
{
current:null
}
在生成Ref对象时,往往有两种方法,在类组件中,我们往往使用React.createRef来生成Ref对象。而useRef通常用于函数组件中Ref对象的生成,这便是React.create与useReact在使用层面上的一个区别。
简单来说:
React.createRef能够在类组件和函数组件中使用useRef仅能够在函数组件中使用
究其原因:
函数组件会随着函数的不断执行而刷新,React.createRef所得到的的Ref对象因重复初始化而无法得到保存,而使用类组件对生命周期进行了分离,不受影响
二、Ref与useRef都能拿来做什么
- 可以获取
DOM元素以及DOM元素的属性 - 获取组件实例以及组件的方法
注:如果Ref获取的是DOM元素,则getref.current为DOM内容。如果获取的是子组件,则getref.current为子组件实例
三、Ref与useRef的使用
Ref的使用有四种方法:字符串、回调函数、React.createRef、useRef
我们一个个来看:
1、字符串(不推荐使用)
创建、使用方式:
- 在标签内通过
ref="Target"定义Ref - 通过
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、回调函数
创建、使用方式:
- 在标签内通过
ref={ (ele) => { this.Target = ele } }定义Ref - 通过
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
创建、使用方式:
- 在函数组件内调用
const Target = React.creatRef(null) - 通过
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
创建、使用方式:
- 导入
useRef钩子 - 在函数组件内调用
const Target = useRef(null) - 通过
Target.current访问获取的DOM或组件实例
useRef所返回的Ref对象在组件中整个生命周期内保持不变,因此能够用于函数组件
import React,{useRef} from 'react';
const Example = () => {
const inputText = useRef(null);
return (
<input ref={inputText.current} />
)
}