总览

当我们在一个函数组件中使用一个字符串作为ref时,会产生"Function components cannot have string refs"错误。为了解决该错误,使用useRef()钩子来得到一个可变的ref对象,这样你就可以在组件中作为ref使用。

这里有个示例用来展示错误是如何发生的。

// App.js

export default function App() {
// A string ref has been found within a strict mode tree.
// ️ Function components cannot have string refs.
// We recommend using useRef() instead.
return (
<div>
<input type="text" id="message" ref="msg" />
</div>
);
}

上述代码片段的问题在于,我们使用了字符串作为ref

useRef

为了解决该错误,使用useRef钩子来获取可变的ref对象。

// App.js

import {useEffect, useRef} from 'react';

export default function App() {
const refContainer = useRef(null); useEffect(() => {
// ️ this is reference to input element
console.log(refContainer.current); refContainer.current.focus();
}, []); return (
<div>
<input type="text" id="message" ref={refContainer} />
</div>
);
}

useRef()钩子可以被传递一个初始值作为参数。该钩子返回一个可变的ref对象,其.current属性被初始化为传递的参数。

需要注意的是,我们必须访问ref对象上的current属性,以获得对我们设置了ref属性的input元素的访问。

当我们传递ref属性到元素上时,比如说,<input ref={myRef} /> 。React将ref对象上的.current属性设置为相应的DOM节点。

useRef钩子创建了一个普通的JavaScript对象,但在每次渲染时都给你相同的ref对象。换句话说,它几乎是一个带有.current属性的记忆化对象值。

不会重新渲染

应该注意的是,当你改变refcurrent属性的值时,不会引起重新渲染。

例如,一个ref不需要包含在useEffect钩子的依赖数组中,因为改变它的current属性不会引起重新渲染。

// App.js

import {useEffect, useRef} from 'react';

export default function App() {
const refContainer = useRef(null); const refCounter = useRef(0); useEffect(() => {
// ️ this is reference to input element
console.log(refContainer.current);
refContainer.current.focus(); // ️ incrementing ref value does not cause re-render
refCounter.current += 1;
console.log(refCounter.current);
}, []); return (
<div>
<input type="text" id="message" ref={refContainer} />
</div>
);
}

例子中的useEffect钩子只运行了2次,因为useRef在其内容发生变化时并没有通知我们。

改变对象的current属性并不会导致重新渲染。

React报错之Function components cannot have string refs的更多相关文章

  1. react 报错的堆栈处理

    react报错 Warning: You cannot PUSH the same path using hash history 在Link上使用replace 原文地址https://reactt ...

  2. refiling失败报错Invalid function: org-preserve-local-variables

    refiling失败报错Invalid function: org-preserve-local-variables,原因: elc,不太清楚 解决办法: 删除org??目录下的elc文件 https ...

  3. mysql插入报错:java.sql.SQLException: Incorrect string value: '\xE6\x9D\xAD\xE5\xB7\x9E...' for column 'address' at row 1

    界面报错: 日志报错: java.sql.SQLException: Incorrect at com.mysql.cj.jdbc.exceptions.SQLError.createSQLExcep ...

  4. React报错之Expected `onClick` listener to be a function

    正文从这开始~ 总览 当我们为元素的onClick属性传递一个值,但是该值却不是函数时,会产生"Expected onClick listener to be a function" ...

  5. react报错this.setState is not a function

    当报错这个的时候就要看函数是否在行内绑定this,或者在constructor中绑定this. 我这里犯的错误的是虽然我在constructor中绑定了this,但是语法写的不正确. 错误示范: co ...

  6. react报错 TypeError: Cannot read property 'setState' of undefined

    代码如下: class test extends Component { constructor(props) { super(props); this.state = { liked: false ...

  7. React报错之Cannot find name

    正文从这开始~ .tsx扩展名 为了在React TypeScript中解决Cannot find name报错,我们需要在使用JSX文件时使用.tsx扩展名,在你的tsconfig.json文件中把 ...

  8. 开启bin-log日志mysql报错:This function has none of DETERMINISTIC, NO SQL解决办法

    开启bin-log日志mysql报错:This function has none of DETERMINISTIC, NO SQL解决办法: 创建存储过程时 出错信息: ERROR 1418 (HY ...

  9. gulp报错task function must be specified

    1.我npm安装了Browserify,tsify和vinyl-source-stream包,想要引用安装的插件,所以就走了引用插件的流程,修改了gulpfiles.js文件,引用流程完毕后,在终端g ...

  10. React报错 :browserHistory doesn't exist in react-router

    由于版本问题,React中history不可用 import { hashHistory } from 'react-router' 首先应该导入react-router-dom包: import { ...

随机推荐

  1. U盘插入电脑后图标是灰色的,打开提示“请将磁盘插入驱动器”

    问题描述: U盘插到win10电脑上后,U盘图标显示灰色,双击打开提示:请将磁盘插入驱动器,无法格式化,在U盘点右键/属性,显示为容量等为0. 解决办法如下: 1.首先要下载一个U盘芯片检测工具chi ...

  2. 使用 Windows 包管理器 (winget) 安装 .Net

    用户可以在 Windows 10 和 Windows 11 计算机上使用 winget 命令行工具来发现.安装.升级.删除和配置应用程序. 此工具是 Windows 程序包管理器服务的客户端接口. 以 ...

  3. 利用POI遍历出层级结构的excel表格

    import java.util.ArrayList; import java.util.List; import org.apache.poi.ss.util.CellRangeAddress; p ...

  4. 多线程的使用(springboot)

    预备知识 业务使用多线程的原因 目的是面对高并发的时候,提高运行速度 场景一: 一个业务逻辑有很多次的循环,每次循环之间没有影响,比如验证1万条url路径是否存在,正常情况要循环1万次,逐个去验证每一 ...

  5. Hive Beeline 命令行参数

    [hadoop@hive ~]$ beeline --help[中文版] The Beeline CLI 支持以下命令行参数: Option Description --autoCommit=[tru ...

  6. JDK 8之前日期和时间的API

    JDK 8之前日期和时间的API(1) System类中的currentTimeMillis():返回当前时间与1970年1月1日0时0分0秒之间以毫秒为单位的时间差.称为时间戳. java.util ...

  7. go channel原理及使用场景

    转载自:go channel原理及使用场景 源码解析 type hchan struct { qcount uint // Channel 中的元素个数 dataqsiz uint // Channe ...

  8. html小总结(哪些可以直接设置高度和宽度)

    (1)当然块级元素是可以直接设置高度和宽度的 块级元素:块级大多为结构性标记 div.h1~h6.ul.ol.dl.form.table.p.hr.pre.address.center.blockqu ...

  9. Nginx实用配置-2

    Nginx配置-2 1.升级Openssl [root@rocky8 ~]# nginx -V #查看现在nginx的OpenSSL版本和编译情况 nginx version: nginx/1.22. ...

  10. CSP-J2022 题解报告

    \(CSP-J2022\) 题解报告 \(T1\) 乘方: 发现 \(2^{32}>10^9\),所以这个题只需要特判 \(a=1\) 的情况为 \(1\),其他直接枚举再判断即可. Code: ...