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


    正文从这开始~

    总览

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

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

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

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

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

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

    DOM元素

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

  • 相关阅读:
    传出神经系统分为哪两类,传出神经的分类与功能
    分布式系统的主键生成方案对比
    Linux入门与进阶(九)
    k8s deployment通用模板
    Spring Boot集成easyposter快速入门Demo
    dp 27 跳跃游戏2 牛客版本
    记一次spark内存泄露问题
    这份Java面试八股文让329人成功进入大厂,堪称2022最强
    C++类和对象(二)(类对象的存储方式)
    从零在win10上测试whisper、faster-whisper、whisperx在CPU和GPU的各自表现情况
  • 原文地址:https://www.cnblogs.com/chuckQu/p/16578306.html