useRef TypeScript - 不可分配到类型 LegacyRef<HTMLDivElement> [英] useRef TypeScript - not assignable to type LegacyRef<HTMLDivElement>
问题描述
我正在尝试将 useRef
与 TypeScript 一起使用,但遇到了一些问题.
使用我的 RefObject
(我假设)我需要访问 current
.(即node.current
)
我已经尝试了以下
const 节点:RefObject
= useRef(null); const node = useRef
(null);
但是当我去设置 ref
时,我总是被告知 X 不可分配到类型 'LegacyRef
return
这不应该仅限于任何一种类型的元素,所以不仅仅是 HTMLDivElement |HTMLFormElement |HTMLInputElement
这应该作为一个例子
import React, { useRef, RefObject } from 'react';功能测试(){//const node = useRef(null);//const 节点:RefObject= useRef(null);const node = useRef
只需导入 REact:
import React, { useRef } from 'react';功能测试() {const node = useRef(null);如果 (节点&&node.current &&node.current.contains()){ console.log(当前访问")}返回<div ref={node}></div>}
我进行了更新.使用 HTMLDivElement
作为通用参数而不是 HTMLElement |空
.此外,contains
需要一个参数.
更新useRef
需要 DOM 元素类型的泛型参数.你不需要使用 |null
因为 RefObject
已经知道 current
可能为 null.
查看下一个类型:
interface RefObject;{只读电流:T |空值}
TS &React 足够聪明,可以判断您的 ref 可能为 null
I am trying to use useRef
with TypeScript but am having some trouble.
With my RefObject
(I assume) I need to access current
. (ie node.current
)
I have tried the following
const node: RefObject<HTMLElement> = useRef(null);
const node = useRef<HTMLElement | null>(null);
but when I go to set the ref
I am always told that X is not assignable to type 'LegacyRef<HTMLDivElement> | undefined'.
return <div ref={ node }>{ children }</div>
Edit: this should not be restricted to any one type of element so not just HTMLDivElement | HTMLFormElement | HTMLInputElement
Edit: This should work as an example
import React, { useRef, RefObject } from 'react';
function Test()
{
// const node = useRef(null);
// const node: RefObject<HTMLElement> = useRef(null);
const node = useRef<HTMLElement | null>(null);
if (
node &&
node.current &&
node.current.contains()
){ console.log("current accessed")}
return <div ref={ node }></div>
}
Just import REact:
import React, { useRef } from 'react';
function Test() {
const node = useRef<HTMLDivElement>(null);
if (
node &&
node.current &&
node.current.contains()
){ console.log("current accessed")}
return <div ref={node}></div>
}
I made an update. Use HTMLDivElement
as generic parameter instead of HTMLElement | null
. Also, contains
expects an argument.
UPDATE
useRef
expects generic argument of DOM element type. You don't need to use | null
because RefObject
already knows that current
might be null.
See next type:
interface RefObject<T> {
readonly current: T | null
}
TS & React are smart enough to figure out that your ref might be null
这篇关于useRef TypeScript - 不可分配到类型 LegacyRef<HTMLDivElement>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!