React报错之Function components cannot have string refs
总览
当我们在一个函数组件中使用一个字符串作为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属性的记忆化对象值。
不会重新渲染
应该注意的是,当你改变ref的current属性的值时,不会引起重新渲染。
例如,一个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的更多相关文章
- react 报错的堆栈处理
react报错 Warning: You cannot PUSH the same path using hash history 在Link上使用replace 原文地址https://reactt ...
- refiling失败报错Invalid function: org-preserve-local-variables
refiling失败报错Invalid function: org-preserve-local-variables,原因: elc,不太清楚 解决办法: 删除org??目录下的elc文件 https ...
- 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 ...
- React报错之Expected `onClick` listener to be a function
正文从这开始~ 总览 当我们为元素的onClick属性传递一个值,但是该值却不是函数时,会产生"Expected onClick listener to be a function" ...
- react报错this.setState is not a function
当报错这个的时候就要看函数是否在行内绑定this,或者在constructor中绑定this. 我这里犯的错误的是虽然我在constructor中绑定了this,但是语法写的不正确. 错误示范: co ...
- react报错 TypeError: Cannot read property 'setState' of undefined
代码如下: class test extends Component { constructor(props) { super(props); this.state = { liked: false ...
- React报错之Cannot find name
正文从这开始~ .tsx扩展名 为了在React TypeScript中解决Cannot find name报错,我们需要在使用JSX文件时使用.tsx扩展名,在你的tsconfig.json文件中把 ...
- 开启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 ...
- gulp报错task function must be specified
1.我npm安装了Browserify,tsify和vinyl-source-stream包,想要引用安装的插件,所以就走了引用插件的流程,修改了gulpfiles.js文件,引用流程完毕后,在终端g ...
- React报错 :browserHistory doesn't exist in react-router
由于版本问题,React中history不可用 import { hashHistory } from 'react-router' 首先应该导入react-router-dom包: import { ...
随机推荐
- Beats:使用 Filebeat 导入 JSON 格式的日志文件
转载自:https://blog.csdn.net/UbuntuTouch/article/details/108504014 在今天的文章中,我来用另外的一种方式来展示如何导入一个 JSON 格式的 ...
- typescript中对象属性可选属性与只读属性与索引签名
可选属性 type类型别名 type 会给一个类型起个新名字. type 有时和 interface 很像,但是可以作用于原始值(基本类型),联合类型,元组以及其它任何你需要手写的类型. interf ...
- C++ 自学笔记 new和delete(动态内存分配)
动态内存分配 Dynamic memoey allocation C++使用new和delete 来申请和释放内存 new:先申请一个空间 int\Stash : 默认构造函数初始化对象 ~:析构函数 ...
- PAT (Basic Level) Practice 1026 程序运行时间 分数 15
要获得一个 C 语言程序的运行时间,常用的方法是调用头文件 time.h,其中提供了 clock() 函数,可以捕捉从程序开始运行到 clock() 被调用时所耗费的时间.这个时间单位是 clock ...
- MES会成为象ERP一样的标准产品吗?
首先ERP不是完全的标准产品,只是标准化程度高低的问题,即使是头部ERP品牌产品也一样,包括SAP对每个企业都有客制,并且随着企业的成长变化也会跟着变,所以SAP就有"Rise With S ...
- spring cron表达式源码分析
spring cron表达式源码分析 在springboot中,我们一般是通过如下的做法添加一个定时任务 上面的new CronTrigger("0 * * * * *")中的参数 ...
- Go实现优雅关机与平滑重启
前言 优雅关机就是服务端关机命令发出后不是立即关机,而是等待当前还在处理的请求全部处理完毕后再退出程序,是一种对客户端友好的关机方式.而执行Ctrl+C关闭服务端时,会强制结束进程导致正在访问的请求出 ...
- HDU2586 How far away ? (树链剖分求LCA)
用树链剖分求LCA的模板: 1 #include<iostream> 2 #include<algorithm> 3 using namespace std; 4 const ...
- MAUI 初体验 联合 WinForm 让家里废弃的手机当做电脑副品用起来
软件效果图 软件架构草图 效果解释:运行 winform 端后 使用 ctrl+c 先复制任何词语,然后ctrl+空格 就可以将翻译结果显示在 安卓,IOS,windows 甚至 mac 任意客户端 ...
- perl chmod
chmod函数改变一列文件的权限.列表的第一个元素必须是数字模式.chmod函数返回成功改变了的文件的数目.如: $cnt = chmod 0755, 'file1', 'file2'; 其中最前面 ...