You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+TypeScript自定义forwardRef输入组件报错原因咨询

自定义可传递Ref的Input组件TypeScript错误原因解析

问题代码

interface IInputProps extends React.HTMLProps<HTMLInputElement> {}

const Input: React.FunctionComponent<IInputProps> = React.forwardRef((props, ref: React.ForwardedRef<HTMLInputElement>) => {
  return <input ref={ref} />;
});

出现的TypeScript错误

Type 'ForwardRefExoticComponent<Pick<IInputProps, "key" | "accept" | "acceptCharset" | "action" | "allowFullScreen" | "allowTransparency" | "alt" | "as" | "async" | "autoComplete" | "autoFocus" | ... 348 more ... | "onTransitionEndCapture"> & RefAttributes<...>>' is not assignable to type 'FunctionComponent<IInputProps>'.
Types of parameters 'props' and 'props' are incompatible.
Type 'PropsWithChildren<IInputProps>' is not assignable to type 'Pick<IInputProps, "key" | "accept" | "acceptCharset" | "action" | "allowFullScreen" | "allowTransparency" | "alt" | "as" | "async" | "autoComplete" | "autoFocus" | ... 348 more ... | "onTransitionEndCapture"> & RefAttributes<...>'.
    Type 'HTMLProps<HTMLInputElement> & { children?: ReactNode; }' is not assignable to type 'RefAttributes<HTMLInputElement>'.
    Types of property 'ref' are incompatible.
        Type 'LegacyRef<HTMLInputElement> | undefined' is not assignable to type 'Ref<HTMLInputElement> | undefined'.
        Type 'string' is not assignable to type 'Ref<HTMLInputElement> | undefined'.ts(2322)

错误原因解析

  1. 组件类型不兼容
    React.forwardRef返回的是ForwardRefExoticComponent类型,它和普通的FunctionComponent类型不匹配。前者会自动为组件添加ref属性(属于RefAttributes),而普通FunctionComponent的props定义里不包含ref,直接赋值就会触发类型不兼容错误。

  2. 过时Ref类型冲突
    你的IInputProps继承了React.HTMLProps<HTMLInputElement>,这个类型包含了过时的字符串Ref(LegacyRef),而forwardRef使用的是现代的Ref类型——现代Ref只支持函数Ref或对象Ref,不接受字符串类型。这就导致了ref属性的类型冲突:LegacyRef中的string类型无法赋值给Ref类型。

修正方案

  • 替换props基类型:用React.InputHTMLAttributes<HTMLInputElement>替代React.HTMLProps<HTMLInputElement>,前者是专门为input元素设计的属性类型,不包含过时的字符串Ref。
  • 正确声明组件类型:要么省略组件的类型声明,让TypeScript自动推断ForwardRefExoticComponent类型;要么显式声明兼容的类型。

修正后的示例代码:

import React from 'react';

interface IInputProps extends React.InputHTMLAttributes<HTMLInputElement> {}

// 自动推断类型(推荐)
const Input = React.forwardRef<HTMLInputElement, IInputProps>((props, ref) => {
  return <input ref={ref} {...props} />;
});

// 或者显式声明类型
const Input: React.ForwardRefExoticComponent<IInputProps & React.RefAttributes<HTMLInputElement>> = 
  React.forwardRef((props, ref) => {
    return <input ref={ref} {...props} />;
  });

内容的提问来源于stack exchange,提问作者Boris Grunwald

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 19:50:42