简体   繁体   English

在其他组件中使用 forwardRef 出现类型错误

[英]Using forwardRef in other component got type error

I got this error:我收到此错误:

Type 'ForwardedRef<unknown>' is not assignable to type 'LegacyRef<HTMLDivElement>'类型“ForwardedRef<unknown>”不可分配给类型“LegacyRef<HTMLDivElement>”

import React from "react";

const Other = React.forwardRef((props, ref) => {
  return (
    <div ref={ref}>
      <h1>Other</h1>
    </div>
  );
});

export default Other;

Is this the right usage?这是正确的用法吗?

Demo: https://codesandbox.io/s/summer-shadow-5ul13e?file=/src/Other.tsx:0-172演示: https://codesandbox.io/s/summer-shadow-5ul13e?file=/src/Other.tsx:0-172

Simply make sure to provide type arguments to forwardRef , as shown for example here :只需确保向 forwardRef 提供类型forwardRef ,如下所示

import React from "react";

const Other = React.forwardRef<HTMLDivElement, unknown>((props, ref) => {
  return (
    <div ref={ref}>{/* Okay */}
      <h1>Other</h1>
    </div>
  );
});

Playground Link 游乐场链接

Initialise useRef with null initially and type <HTMLDivElement> .最初使用null初始化useRef并键入<HTMLDivElement> Also, apply type <HTMLDivElement> to forwardRef as well.此外,还将类型<HTMLDivElement>应用于forwardRef Check on mount if ref is assigned correctly.检查 mount 是否正确分配了ref

Here is the Sandbox Link这是沙盒链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM