正文从这开始~

总览

当我们用一个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. Django序列化组件与数据批量操作与简单使用Forms组件

    目录 SweetAlert前端插件 Django自带的序列化组件 批量数据操作 分页器与推导流程 Forms组件之创建 Forms组件之数据校验 Forms组件之渲染标签 Forms组件之信息展示 S ...

  2. 开源流程引擎Camunda BPM如何扩展数据库表

    前言 在使用开源流程引擎(如:JBPM.Activiti.Flowable.Camunda等)的时候,经常会遇到这样的需求,我们需要按照业务需求增加一张数据库的表,而且这张表是跟工作流引擎有交互的(注 ...

  3. php三行代码解决输入地址给出经纬度

    //获取地址经纬度坐标 public function getAddress() { $ak = 'GPIrsdfZ-UNLRP-VBBDB-V3AGK-XL5KO-5DBNY'; $address  ...

  4. 论文解读(GraphMAE)《GraphMAE: Self-Supervised Masked Graph Autoencoders》

    论文信息 论文标题:GraphMAE: Self-Supervised Masked Graph Autoencoders论文作者:Zhenyu Hou, Xiao Liu, Yukuo Cen, Y ...

  5. 从零开始实现lmax-Disruptor队列(三)多线程消费者WorkerPool原理解析

    MyDisruptor V3版本介绍 在v2版本的MyDisruptor实现多消费者.消费者组间依赖功能后.按照计划,v3版本的MyDisruptor需要支持多线程消费者的功能. 由于该文属于系列博客 ...

  6. element ui FORM表单

    form表单 Form-Item Slot [label] 旧版语法 <el-form-item label="活动名称" prop="name"> ...

  7. idea 在创建maven时没有src的解决方法

    在创建maven时    加上archetypeCatalog=internal

  8. NC15052 求最值

    NC15052 求最值 题目 题目描述 给你一个长为 \(n\) 的序列 \(a\) 定义 \(f(i,j)=(i-j)^2+g(i,j)^2\) \(g\) 是这样的一个函数 求最小的 \(f(i, ...

  9. Unity3D学习笔记7——GPU实例化(2)

    目录 1. 概述 2. 详论 2.1. 实现 2.2. 解析 3. 参考 1. 概述 在上一篇文章<Unity3D学习笔记6--GPU实例化(1)>详细介绍了Unity3d中GPU实例化的 ...

  10. HashMap存储自定义类型键值和LinkedHashMap集合

    HashMap存储自定义类型键值 1.当给HashMap中存放自定义对象时,如果自定义对象是键存在,保证键唯一,必须复写对象的hashCode和equals方法. 2.如果要保证map中存放的key和 ...