正文从这开始~

总览

当我们用一个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. TKE qGPU 通过 CRD 管理集群 GPU 卡资源

    作者 刘旭,腾讯云高级工程师,专注容器云原生领域,有多年大规模 Kubernetes 集群管理经验,现负责腾讯云 GPU 容器的研发工作. 背景 目前 TKE 已提供基于 qGPU 的算力/显存强隔离 ...

  2. 基于.NetCore开发博客项目 StarBlog - (10) 图片瀑布流

    系列文章 基于.NetCore开发博客项目 StarBlog - (1) 为什么需要自己写一个博客? 基于.NetCore开发博客项目 StarBlog - (2) 环境准备和创建项目 基于.NetC ...

  3. conda install和pip install区别

    conda ≈ pip(python包管理) + virtualenv(虚拟环境) + 非python依赖包管理 级别不一样conda和yum比较类似,可以安装很多库,不限于Python.conda是 ...

  4. TypeScript(3)基础类型

    基础类型 TypeScript 支持与 JavaScript 几乎相同的数据类型,此外还提供了实用的枚举类型方便我们使用. 布尔值 最基本的数据类型就是简单的true/false值,在JavaScri ...

  5. 打字练习-编程语言关键字系列-java

    小编整理的java关键字,内容如下:abstract, assert, boolean, break, byte, case, catch, char, class, const, continue, ...

  6. 使用aggregation API扩展你的kubernetes API

    Overview What is Kubernetes aggregation Kubernetes apiserver aggregation AA 是Kubernetes提供的一种扩展API的方法 ...

  7. rhel安装程序

    Linux下软件分类     rpm软件包,包管理器 yum     deb软件包,包管理器 apt     源代码软件包            一般为".tar.gz".&quo ...

  8. 霍普菲尔得神经网络(Hopfield Neural Network)

    设计一个反馈网络存储下列目标平衡点: T = [ 1  -1; -1  1 ]; 并用6组任意随机初始列矢量,包括一组在目标平衡点连线的垂直平分线上的一点作为输入矢量对所设计的网络的平衡点进行测试,观 ...

  9. linux 运行.sh出现 Permission denied

    执行.sh脚本时提示如下错误: [root@Dolen2021 redis]# ./startRedis.sh -bash: ./startRedis.sh: Permission denied [r ...

  10. ABAP BAPI 复制标准项目模板实现项目立项

    一.复制标准项目模板实现项目立项 因为CJ20N录屏存在困难,所以想通过BDC实现复制项目模板创建项目立项行不通,因此需要通过BAPI解决. 因为项目立项包含:项目定义.WBS.网络.作业,因此需要分 ...