首页 > 解决方案 > React.forwardRef转发ref后如何定义Input组件ref的类型?

问题描述

代码

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

错误信息

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.

如何定义 Input 组件 ref 的类型?

标签: reactjstypescriptantd

解决方案


any如果您没有在函数定义/组件中使用它,则不需要为 props 添加通用参数。

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

关于 forwardRef 的简短说明。它是一个泛型函数,具有 ref 和 props 类型的类型参数。

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

你会对泛型参数(ref 然后是 props)的顺序感到困惑,这与函数参数(props 然后 ref)的顺序相反。


推荐阅读