简体   繁体   中英

Using forwardRef in other component got type error

I got this error:

Type 'ForwardedRef<unknown>' is not assignable to type '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

Simply make sure to provide type arguments to forwardRef , as shown for example here :

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> . Also, apply type <HTMLDivElement> to forwardRef as well. Check on mount if ref is assigned correctly.

Here is the Sandbox Link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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