React Usage Issue

Published: · LastMod: January 04, 2023 · 311 words

not assignable to type LegacyRef<xxxxx> 🔗

useRef定义一个ref时,报不能推断类型

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import React, { useRef, RefObject } from 'react';

function Test() 
{
    const node = useRef<HTMLElement>(null);

    if (
        node &&
        node.current &&
        node.current.contains()
    ){ console.log("current accessed")}

    return <div ref={ node }></div>
}

因为useRef是使用HTMLElement定义的泛型,所以说不能推断,改成ref所对应的标签泛型就可以了

Cannot assign to ‘current’ because it is a read-only property 🔗

当在react中使用useRef定义ref时,报这样的错误, 因为结果走到React.RefObject

useRef有这3种定义

1
2
3
4
5
function useRef<T>(initialValue: T): MutableRefObject<T>;

function useRef<T>(initialValue: T|null): RefObject<T>;

function useRef<T = undefined>(): MutableRefObject<T | undefined>;
  1. useRef初始值设为null
  2. useRef定义了一个初始的类型
1
2
3
const elem = useRef<HTMLDivElement>(null);

type Test = typeof elem; // Test = React.RefObject<HTMLDivElement>
1
2
error expect@29.3.1: The engine "node" is incompatible with this module. Expected version "^14.15.0 || ^16.10.0 || >=18.0.0". Got "17.5.0"
error Found incompatible module.

如果是使用yarn安装时加上yarn --ignore-engines