Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
655 views
in Technique[技术] by (71.8m points)

reactjs - How to define the type of the Input component ref after the React.forwardRef forwards the ref?

Code

import React, { forwardRef, useRef } from "react";

import { Input } from "antd";

const Child = forwardRef<HTMLInputElement, any>((props, ref) => {
  // typescript error
  return <Input ref={ref} />;
});

const Parents = () => {
  const inputRef = useRef<HTMLInputElement>(null);
  return <Child ref={inputRef} />;
};

export default Parents

Error message

TS2322: Type '((instance: HTMLInputElement) => void) | MutableRefObject<HTMLInputElement>' is not assignable to type 'LegacyRef<Input>'. ??Type '(instance: HTMLInputElement) => void' is not assignable to type 'LegacyRef<Input>'. ????Type '(instance: HTMLInputElement) => void' is not assignable to type '(instance: Input) => void'. ??????Types of parameters 'instance' and 'instance' are incompatible. ????????Type 'Input' is missing the following properties from type 'HTMLInputElement': accept, align, alt, autocomplete, and 284 more.

How do I define the type of the Input component ref?

question from:https://stackoverflow.com/questions/65948412/how-to-define-the-type-of-the-input-component-ref-after-the-react-forwardref-for

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You don't need to add a generic parameter any for props if you are not using it in the function definition/component.

const Child = forwardRef<HTMLInputElement>((props, ref) => {
  return <Input ref={ref} />;
});

A short note on forwardRef. It is a generic function that has type parameters of ref and props types.

const comp = React.forwardRef<RefType, PropsType>((props, ref) => {
  return someComp;
});

You will be confused about the ordering of the generic parameter (ref and then props) which is the opposite of the ordering of the function parameters (props and then ref).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...