正文从这开始~

总览

当我们用一个null值初始化一个ref,但在其类型中不包括null时,就会发生"Cannot assign to 'current' because it is a read-only property"错误。为了解决该错误,请在ref的类型中包含null。比如说,const ref = useRef<string | null>(null)

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

// App.tsx
import {useEffect, useRef} from 'react'; const App = () => {
const ref = useRef<string>(null); useEffect(() => {
// ️ Error: Cannot assign to 'current' because it is a read-only property.ts(2540)
ref.current = 'hello';
}, []); return (
<div>
<h2>hello world</h2>
</div>
);
}; export default App;

上面例子的问题在于,当我们将null作为初始值传递到useRef钩子中时,并且我们传递给钩子的泛型中没有包括null类型,我们创建了一个不可变的ref对象。

正确的泛型

为了解决该错误,我们必须在传递给钩子的泛型中包括null类型。

// App.tsx
import {useEffect, useRef} from 'react'; const App = () => {
// ️ include null in the ref's type
const ref = useRef<string | null>(null); useEffect(() => {
ref.current = 'hello';
}, []); return (
<div>
<h2>hello world</h2>
</div>
);
}; export default App;

ref的类型中,我们使用联合类型来包括null类型,这使它成为可变ref对象。

现在这个例子中ref的类型是字符串或null,它的current属性可以赋值为这两种类型中的任意一种的值。

DOM元素

如果你的引用指向一个DOM元素,情况也是一样的。如果你需要改变refcurrent属性的值,你必须将钩子的类型定为 const ref = useRef<HTMLElement | null>(null)

注意,如果你不直接赋值给它的current属性,你不必在 ref 的类型中包含 null

// App.tsx
import {useEffect, useRef} from 'react'; const App = () => {
const ref = useRef<HTMLInputElement>(null); useEffect(() => {
ref.current?.focus();
}, []); return (
<div>
<input ref={ref} type="text" defaultValue="" />
</div>
);
}; export default App;

上述例子中的ref是用来聚焦input元素的。因为没有对其.current属性进行赋值,所以没有必要在其类型中包含null

React报错之Cannot assign to 'current' because it is a read-only property的更多相关文章

  1. react 报错的堆栈处理

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

  2. vue运行报错error:Cannot assign to read only property 'exports' of object '#<Object>'

    用weex做项目的时候,npm start 之后一直报错error:Cannot assign to read only property 'exports' of object '#<Obje ...

  3. Spring+Hibernate4 Junit 报错No Session found for current thread

    论坛上有另外一篇更全面的帖子,jinnianshilongnian写的:http://www.iteye.com/topic/1120924 本文的环境是:  spring-framework-3.1 ...

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

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

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

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

  6. React报错之Cannot find name

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

  7. React报错之Cannot find namespace context

    正文从这开始~ 总览 在React中,为了解决"Cannot find namespace context"错误,在你使用JSX的文件中使用.tsx扩展名,在你的tsconfig. ...

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

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

  9. React报错:Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix,

    今天在开发时报了以下错误,记录一下 我们不能在组件销毁后设置state,防止出现内存泄漏的情况 出现原因直接告诉你了,组件都被销毁了,还设置个锤子的state啊 解决方案: 利用生命周期钩子函数:co ...

随机推荐

  1. Fail2ban 使用Fail2ban监禁SSH服务的恶意IP

    Fail2ban自带了很多服务的过滤器(filter)和动作(action),它已经帮你做好了,所以一般情况下我们无需定义,直接引用即可. 这边只是一个示例. 系统版本:Ubuntu 16.04.5 ...

  2. [2-SAT]编码

    题意:给n个01字符串,每个最多包含1个'?',能否构造出满足两两不存在一个是另一个前缀的方案. 思路: 2-SAT+trie树优化建图 把每个字符串拆成i,i+n,如果不存在'?',就硬搞出两种情况 ...

  3. Python Flask项目步骤

    构建flask项目步骤 步骤一:构建基础项目框架 创建manage.py文件 from flask import Flask app = Flask(__name__) ""&qu ...

  4. Keil软件下用Jlink无法识别芯片

    Keil软件下用Jlink无法识别芯片 硬件:正点原子探索者 软件:keil J-Link固件版本:V9.40 J-Link V6.94b驱动:下载地址 跟着视频教程走,发现的第一个问题就是这个,记录 ...

  5. NB-IoT/LoRa/eMTC和蓝牙/WiFi的关系是互补还是替代?

    近年来,相继出现了许多物联网技术.WiFi.蓝牙.NB-IoT.LoRa.eMTC和其他技术为IoT实践提供了一流的技术支持通讯端口.拥有这么多技术,能够互相替代吗?还是能起到互补的作用?为低功耗广域 ...

  6. Spring Security整合企业微信的扫码登录,企微的API震惊到我了

    本文代码: https://gitee.com/felord/spring-security-oauth2-tutorial/tree/wwopen/ 现在很多企业都接入了企业微信,作为私域社群工具, ...

  7. MAC NGINX PHP XDEBUG

    1. 安装 homebrew 2. 安装nginx ; 终端运行 brew install nginx: 1)给nginx 设置管理员权限:如果不设置管理员权限,80端口是不能监听的: #这里的目录根 ...

  8. 【Github】 Github修改仓库的基本信息

    前言 我们通常在刚开始了解学习使用github时,一般都是测试的使用,有时我们向里面添加了一些代买,如果想要修改信息并且是删除仓库重新创建提交,可以采用下面方法修改仓库信息,名称.描述等. 修改仓库描 ...

  9. SAP APO-部署选项

    SAP SCM Server安装提供SAP APO功能模块的所有功能. 在SAP APO的附加部署模型中,以下组件可用作SAP APO工具的一部分- OTE-在附加部署模型中,无法通过SAP SCM服 ...

  10. UiPath鼠标操作图像的介绍和使用

    一.鼠标(mouse)操作的介绍 模拟用户使用鼠标操作的一种行为,例如单击,双击,悬浮.根据作用对象的不同我们可以分为对元素的操作.对文本的操作和对图像的操作 二.鼠标对图像的操作在UiPath中的使 ...