前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >React报错之Cannot assign to 'current' because a read-only property

React报错之Cannot assign to 'current' because a read-only property

作者头像
chuckQu
发布2022-08-19 16:42:41
9710
发布2022-08-19 16:42:41
举报
文章被收录于专栏:前端F2E

原文链接:https://bobbyhadz.com/blog/react-cannot-assign-to-current-because-read-only-property[1]

作者:Borislav Hadzhiev[2]

正文从这开始~

总览

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

react-cannot-assign-to-current-because-read-only.png

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

代码语言:javascript
复制
// 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类型。

代码语言:javascript
复制
// 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

代码语言:javascript
复制
// 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

参考资料

[1]

https://bobbyhadz.com/blog/react-cannot-assign-to-current-because-read-only-property: https://bobbyhadz.com/blog/react-cannot-assign-to-current-because-read-only-property

[2]

Borislav Hadzhiev: https://bobbyhadz.com/about

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2022-08-11,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 前端F2E 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 总览
  • 正确的泛型
  • DOM元素
    • 参考资料
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档