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

TypeScript中使用forwardRef传递Props的类型错误修复方案

解决React forwardRef的TypeScript类型不匹配错误

问题出在forwardRef的泛型参数缺失——你只指定了ref对应的元素类型,没有声明组件的Props类型,导致TypeScript默认认为props是空对象{},和你定义的Props类型冲突。

修复步骤:

  1. 确保Props类型已正确定义
    先明确你的Props类型结构,比如:

    import { Dispatch, SetStateAction } from 'react';
    
    type Props = {
      comment: string;
      setComment: Dispatch<SetStateAction<string>>;
    };
    
  2. 给forwardRef传入完整的泛型参数
    修改AddComment组件的导出语句,同时指定ref元素类型和Props类型:

    import { forwardRef, Ref } from 'react';
    
    function AddComment({ comment, setComment }: Props, ref: Ref<HTMLDivElement>) {
      return (<div ref={ref}>
        // code...
      </div>)
    }
    // 新增Props作为第二个泛型参数
    export default forwardRef<HTMLDivElement, Props>(AddComment)
    

为什么这样能解决?

forwardRef的类型ForwardRefRenderFunction需要两个泛型参数:

  • 第一个参数:ref指向的DOM元素类型(这里是HTMLDivElement)
  • 第二个参数:组件接收的props类型(这里是你的Props)

之前只传第一个参数时,TypeScript会默认props类型为{},自然和你的Props类型不兼容,补上第二个泛型参数后,类型推断就正确了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 23:48:14