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

在React组件中使用forwardRef遇类型错误,咨询正确用法

关于React forwardRef的类型错误及用法疑问

问题描述

遇到如下TypeScript错误:

Type 'ForwardedRef' is not assignable to type 'LegacyRef'

对应的代码示例:

import React from "react";

const Other = React.forwardRef((props, ref) => {
  return (
    <div ref={ref}>
      <h1>Other</h1>
    </div>
  );
});

export default Other;

请问这是forwardRef的正确用法吗?


问题原因与正确用法

这不是forwardRef在TypeScript环境下的正确写法,错误根源是没有为forwardRef指定泛型类型——TS无法自动推断出ref关联的DOM元素类型,默认把ref判定为ForwardedRef<unknown>,和div元素要求的LegacyRef<HTMLDivElement>类型不兼容。

正确写法需要给forwardRef传入泛型参数,明确ref对应的元素类型:

import React from "react";

// 第一个泛型指定ref目标为HTMLDivElement,第二个是组件props类型(无props则用{})
const Other = React.forwardRef<HTMLDivElement, {}>((props, ref) => {
  return (
    <div ref={ref}>
      <h1>Other</h1>
    </div>
  );
});

export default Other;

补充说明

  • 第一个泛型参数:必须和组件内挂载ref的DOM元素类型一致,比如按钮对应HTMLButtonElement、输入框对应HTMLInputElement
  • 第二个泛型参数:对应组件的props类型,若组件有自定义props(比如{ text: string }),直接替换{}即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 10:21:12