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

我正在尝试useRef与 TypeScript一起使用,但遇到了一些麻烦。

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

我已经尝试了以下

  • const node: RefObject<HTMLElement> = useRef(null);
  • const node = useRef<HTMLElement | null>(null);

但是当我去设置时,ref我总是被告知 Xis 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期待一个论点。

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

看下一个类型:

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

TS 和 React 足够聪明,可以确定您的 ref 可能为空

  • thank you this does work. If you could, please provide additional details as to *why* this works and why one should use this interface. thank you
  • HTMLElement interface is a parent interface for all html elements. It does not work because you are unable to create HTMLElement literally. You can only create HTMLDivElement, HTMLSpanElement, HTMLAnchorElement etc .... So React/JSX only can accept HTML{element}Element. For instance, it complains that HTMLElement does not have `allign` property. Hover mouse on ref attribute in your IDE press Ctrl and click on ref attribute. It should redirect you to ref types

以上是useRefTypeScript-不可分配给类型LegacyRef&lt;HTMLDivElement&gt;的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>