我们相信:世界是美好的,你是我也是。平行空间的世界里面,不同版本的生活也在继续...

ref引用是react中出现的一个新的概念,这个概念可以用于链接react世界和传统页面写法的世界。可以说ref可以用于沟通react逻辑和传统页面逻辑的神奇魔法大门。在类式组件和函数式组件中,都存在着ref的概念,但是使用方式是有所不同的。本文则主要介绍在类式组件中,使用ref的方式。

苏南大叔:react项目,传统类组件如何使用createRef()创建ref引用? - react-createref-ref
react项目,传统类组件如何使用createRef()创建ref引用?(图6-1)

大家好,这里是苏南大叔的程序如此灵动博客,这里记录苏南大叔和计算机代码的故事。本文通过一个类式组件的例子,说明如何使用createRef()来创建一个ref引用,并且读取相关数据。测试环境:create-react-app@5.0.1react@18.2.0react-dom@18.2.0node@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} />

苏南大叔:react项目,传统类组件如何使用createRef()创建ref引用? - inputref定义
react项目,传统类组件如何使用createRef()创建ref引用?(图6-2)

调用ref.current

react中,所有的ref都有个current值,这个表示的是真正的引用对象。比如在上个例子中,这个真正的引用对象就是input(传统意义上html里面的input对象,而不是react包装过的input)。

读取ref.current属性

经常使用ref.current.value来获得inputvalue值。

if (this.inputRef.current) {
  console.log(this.inputRef.current.value);
}

因为ref的默认值是null,所以如果直接调用.current.value的话,可能会报错。另外,因为.current代表的对象是什么都有可能,所以,也不一定能获得.value属性。

苏南大叔:react项目,传统类组件如何使用createRef()创建ref引用? - 读取current值
react项目,传统类组件如何使用createRef()创建ref引用?(图6-3)

调用ref.current属性

因为在本文中,ref是个输入框,传统的页面逻辑里面,输入框有很多方法可以调用,其中一个就是聚焦(focus())。

this.inputRef.current.focus();

苏南大叔:react项目,传统类组件如何使用createRef()创建ref引用? - inputref-focus
react项目,传统类组件如何使用createRef()创建ref引用?(图6-4)

测试代码

如下代码是在传统类组件中,定义和使用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项目,传统类组件如何使用createRef()创建ref引用? - 总体代码截图
react项目,传统类组件如何使用createRef()创建ref引用?(图6-5)

特殊说明

在更早期的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-ref

react官方有对使用字符串的警告的说明文章:

苏南大叔:react项目,传统类组件如何使用createRef()创建ref引用? - ref-error
react项目,传统类组件如何使用createRef()创建ref引用?(图6-6)

@deprecated — https://reactjs.org/docs/refs-and-the-dom.html#legacy-api-string-refs
“refs”已弃用。ts(6385)

react官方有对refs的写法弃用的说明文章:

相关链接

结束语

react里面ref的创建,分为两个分支,类式组件和函数式组件里面,方式是完全不同的。在使用的时候,都是通过.current来获得引用对象的,但是引用对象是个dom,还是个js变量,这个还有待考证。

更多react经验文章,请点击苏南大叔的经验文章:

如果本文对您有帮助,或者节约了您的时间,欢迎打赏瓶饮料,建立下友谊关系。
本博客不欢迎:各种镜像采集行为。请尊重原创文章内容,转载请保留作者链接。

 【福利】 腾讯云最新爆款活动!1核2G云服务器首年50元!

 【源码】本文代码片段及相关软件,请点此获取更多信息

 【绝密】秘籍文章入口,仅传授于有缘之人   react