react项目,传统类组件如何使用createRef()创建ref引用?
发布于 作者:苏南大叔 来源:程序如此灵动~
ref引用是react中出现的一个新的概念,这个概念可以用于链接react世界和传统页面写法的世界。可以说ref可以用于沟通react逻辑和传统页面逻辑的神奇魔法大门。在类式组件和函数式组件中,都存在着ref的概念,但是使用方式是有所不同的。本文则主要介绍在类式组件中,使用ref的方式。

大家好,这里是苏南大叔的程序如此灵动博客,这里记录苏南大叔和计算机代码的故事。本文通过一个类式组件的例子,说明如何使用createRef()来创建一个ref引用,并且读取相关数据。测试环境:create-react-app@5.0.1,react@18.2.0,react-dom@18.2.0,node@16.14.2。
创建和引用
创建一个ref,使用的是createRef()方法,它是定义在React对象上的,不用单独引用。一般来说,这个ref是会附加在某个html对象上的。但是,也可以附加在某个js对象上。目前本文描述的是头一种最常见的情况,附在某个html对象(input)上。
import React, { Component } from 'react'
export default class Child extends Component {
constructor(props) {
super(props);
this.inputRef = React.createRef();
}
render() {
return (
<div className="Child">
<input
type="text"
ref={this.inputRef}
/>
</div>
)
}
}关键代码:
this.inputRef = React.createRef();<input type="text" ref={this.inputRef} />
调用ref.current
在react中,所有的ref都有个current值,这个表示的是真正的引用对象。比如在上个例子中,这个真正的引用对象就是input(传统意义上html里面的input对象,而不是react包装过的input)。
读取ref.current属性
经常使用ref.current.value来获得input的value值。
if (this.inputRef.current) {
console.log(this.inputRef.current.value);
}因为ref的默认值是null,所以如果直接调用.current.value的话,可能会报错。另外,因为.current代表的对象是什么都有可能,所以,也不一定能获得.value属性。

调用ref.current属性
因为在本文中,ref是个输入框,传统的页面逻辑里面,输入框有很多方法可以调用,其中一个就是聚焦(focus())。
this.inputRef.current.focus();
测试代码
如下代码是在传统类组件中,定义和使用ref的简单例子。
import React, { Component } from 'react'
export default class Child extends Component {
constructor(props) {
super(props);
this.inputRef = React.createRef();
}
focusInput() {
this.inputRef.current.focus();
}
getData() {
if (this.inputRef.current) {
console.log(this.inputRef.current.value);
}
}
render() {
return (
<div className="Child">
<input
type="text"
ref={this.inputRef}
defaultValue="defaultValue"
onChange={this.getData.bind(this)}
/>
<input
type="button"
value="Focus the input"
onClick={this.focusInput.bind(this)}
/>
</div>
)
}
}在输入框里面修改文字的时候,会有console.log输出其文字,点击按钮可以主动要求输入框实现聚焦功能(这个和react的思路是完全背驰的)。

特殊说明
在更早期的react代码里面,创建ref是不需要createRef()的,可以直接写个字符串也是可以的。比如:
<input ref='target'/>调用的时候,使用this.refs[]数组来使用。
this.refs["target"].current.value但是,这种写法已经被弃用了。如果使用的话,可能会收到一些错误提示信息。例如:
Warning: A string ref, "target", has been found within a strict mode tree. String refs are a source of potential bugs and should be avoided. We recommend using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-refreact官方有对使用字符串的警告的说明文章:

@deprecated ― https://reactjs.org/docs/refs-and-the-dom.html#legacy-api-string-refs
“refs”已弃用。ts(6385)react官方有对refs的写法弃用的说明文章:
相关链接
- https://newsn.net/say/react-state.html
- https://newsn.net/say/react-memo.html
- https://newsn.net/say/react-bind.html
- https://newsn.net/say/react-pure-component.html
- https://newsn.net/say/create-react-app.html
结束语
在react里面ref的创建,分为两个分支,类式组件和函数式组件里面,方式是完全不同的。在使用的时候,都是通过.current来获得引用对象的,但是引用对象是个dom,还是个js变量,这个还有待考证。
更多react经验文章,请点击苏南大叔的经验文章: