【问题标题】:useRef TypeScript - not assignable to type LegacyRef<HTMLDivElement>useRef TypeScript - 不可分配给类型 LegacyRef<HTMLDivElement>
【发布时间】:2021-07-01 22:06:22
【问题描述】:

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

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

我已经尝试了以下

  • const node: RefObject&lt;HTMLElement&gt; = useRef(null);
  • const node = useRef&lt;HTMLElement | null&gt;(null);

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

return &lt;div ref={ node }&gt;{ children }&lt;/div&gt;

编辑:这不应仅限于任何一种类型的元素,而不仅仅是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>
}

【问题讨论】:

  • olease 提供可重现的示例
  • @captain-yossarian 请查看最新编辑

标签: reactjs typescript tsx


【解决方案1】:

以上方法都不适合我,但事实证明解决方案非常简单......

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

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

const ref = useRef<HTMLDivElement>(null);

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

【讨论】:

    【解决方案2】:

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

    const node = useRef<HTMLIFrameElement>(null);
    

    【讨论】:

    • 我只需要添加默认的null 值。立即修复了我的错误
    【解决方案3】:

    只需导入 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 足够聪明,可以确定您的 ref 可能为空

    【讨论】:

    • 我很欣赏这个答案,这确实适用于我提供的示例,但不幸的是我需要添加到我的示例中。我的道歉
    • 如果您想修改答案,我已经修改了示例
    • 谢谢你这确实有效。如果可以,请提供更多详细信息,说明为什么这有效,以及为什么应该使用这个界面。谢谢
    • 感谢您的更新,我会接受这个答案。我想我了解null 的部分我对为什么HTMLDivElement 能够处理refHTMLElement 不是更感兴趣
    • HTMLElement 接口是所有 html 元素的父接口。它不起作用,因为您无法从字面上创建 HTMLElement。你只能创建 HTMLDivElement、HTMLSpanElement、HTMLAnchorElement 等......所以 React/JSX 只能接受 HTML{element}Element。例如,它抱怨 HTMLElement 没有 allign 属性。将鼠标悬停在 IDE 中的 ref 属性上,按 Ctrl 并单击 ref 属性。它应该将您重定向到 ref 类型
    【解决方案4】:

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

    const node = useRef<HTMLElement>();
    

    【讨论】:

      猜你喜欢
      • 2023-01-03
      • 2021-09-05
      • 2022-01-15
      • 1970-01-01
      • 1970-01-01
      • 2020-08-16
      • 2020-04-26
      • 1970-01-01
      • 2022-12-01
      相关资源
      最近更新 更多