useRef TypeScript - 不可分配给类型 LegacyRef<HTMLDivElement>

useRef TypeScript - not assignable to type LegacyRef<HTMLDivElement>

我正在尝试将 useRef 与 TypeScript 一起使用,但遇到了一些问题。

我的 RefObject(我假设)我需要访问 current。 (即node.current

我试过以下方法

但是当我去设置 ref 时,我总是被告知 X is not assignable to type 'LegacyRef<HTMLDivElement> | undefined'.

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

编辑:这不应仅限于任何一种类型的元素,而不仅仅是 HTMLDivElement | HTMLFormElement | HTMLInputElement

编辑:这应该可以作为示例

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>
}

只需导入 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>
}

我更新了。使用 HTMLDivElement 作为通用参数而不是 HTMLElement | null。此外,contains 需要一个参数。

更新 useRef 需要 DOM 元素类型的通用参数。您不需要使用 | null 因为 RefObject 已经知道 current 可能为空。

查看下一个类型:

interface RefObject<T> {
  readonly current: T | null
}

TS 和 React 足够聪明,可以判断出您的引用可能为 null

关键是使用 HTMLElement 和 undefined 进行初始化

const node = useRef<HTMLElement>();

我来这里寻求有关 iframe 引用的帮助。也许这个解决方案会帮助其他正在寻找同样东西的人。我用 HTMLIFrameElement 替换了 HTMLDivElement 所以:

const node = useRef<HTMLIFrameElement>(null);

None 以上对我有用,但事实证明解决方案非常简单...

我做错的只是没有在 useRef 初始化中明确包含“null”作为参数(它需要 null,而不是 undefined)。 另外你不能使用“HTMLElement”作为你的引用类型,你必须更具体,所以对我来说它是“HTMLDivElement”例如)。

所以对我来说工作代码是这样的:

const ref = useRef<HTMLDivElement>(null);

return <div ref={ref}> Some Content... </div>

同样代表<svg>个元素:

const ref = useRef<SVGSVGElement>(null)
...
<svg ref={ref} />