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>;
|
- useRef初始值设为null
- 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