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 { ...
随机推荐
- 几篇关于MySQL数据同步到Elasticsearch的文章---第三篇:logstash_output_kafka:Mysql同步Kafka深入详解
文章转载自: https://mp.weixin.qq.com/s?__biz=MzI2NDY1MTA3OQ==&mid=2247484411&idx=1&sn=1f5a371 ...
- jq修改多个css样式
$("#xxx").css({"属性名称": "属性值", "属性名称": "属性值" });
- P1073 [NOIP2009 提高组] 最优贸易 (最短路spfa)
本题就是在一条1-n的路径上找p,q(先经过p),使得q-p最大. 考虑建正反图,正图上求出d[x],表示1-x的路径经过的节点最小值,反图上则从n开始求出f[x],x-n的最大值,最后枚举断点i,取 ...
- SQL抽象语法树及改写场景应用
1 背景 我们平时会写各种各样或简单或复杂的sql语句,提交后就会得到我们想要的结果集.比如sql语句,"select * from t_user where user_id > 10 ...
- vue+element-ui后台管理系统模板
vue+element-ui后台管理系统模板 前端:基于vue2.0+或3.0+加上element-ui组件框架 后端:springboot+mybatis-plus写接口 通过Axios调用接口完成 ...
- el-form-item label中的字体样式设置格式
1.设置前的代码 <el-form-item label="管理员密码" prop="password" > <el-input type=& ...
- sql面试50题------(1-10)
文章目录 1.查询课程编号'01'比课程编号'02'成绩高的所有学生学号 2.查询平均成绩大于60分得学生的学号和平均成绩 3.查询所有学生的学号,姓名,选课数,总成绩 4.查询姓"猴&qu ...
- Spring源码知识
bean的生命周期: 实例化:在堆空间中申请内存,使用反射来实现:(createBeanInstance) 自定义属性赋值(setter).容器对象属性赋值(invokeAwareMethods) 前 ...
- vulnhub靶场之THALES: 1
准备: 攻击机:虚拟机kali.本机win10. 靶机:THALES: 1,网段地址我这里设置的桥接,所以与本机电脑在同一网段,下载地址:https://download.vulnhub.com/th ...
- pytorch 环境配置
一.下载Anaconda 二.添加清华镜像 # 添加清华镜像 conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anac ...