You need to enable JavaScript to run this app. React+TypeScript如何根据props动态约束ForwardRef的ref类型
优惠活动
大模型
产品
解决方案
定价
更多

React+TypeScript如何根据props动态约束ForwardRef的ref类型

实现方案

你需要通过判别式联合类型定义两种互斥的Props场景,再配合组件函数重载,实现ref类型和label属性的关联约束,完整实现代码如下:

import { forwardRef, ForwardedRef, useRef } from 'react';

// 定义两种互斥的Props场景
type ButtonProps = {
  label?: never;
};
type LabelProps = {
  label: string;
};
type Props = ButtonProps | LabelProps;

// 定义组件重载,分别绑定不同场景下的ref类型
function DynamicComponent(props: ButtonProps & { ref?: ForwardedRef<HTMLButtonElement> }): JSX.Element;
function DynamicComponent(props: LabelProps & { ref?: ForwardedRef<HTMLLabelElement> }): JSX.Element;

// 组件内部实现
const DynamicComponent = forwardRef<
  HTMLButtonElement | HTMLLabelElement,
  Props
>((props, ref) => {
  if ('label' in props) {
    return (
      <label ref={ref as ForwardedRef<HTMLLabelElement>}>
        {props.label}
      </label>
    );
  }
  return (
    <button ref={ref as ForwardedRef<HTMLButtonElement>}>BUTTON</button>
  );
});

效果验证

调用组件时会自动匹配对应重载,不符合的ref类型会直接触发TS报错:

export default function App() {
  const btnRef = useRef<HTMLButtonElement>(null); // 合法
  const labelRef = useRef<HTMLLabelElement>(null); // 合法

  // 以下错误写法会触发类型提示
  // const wrongRef1 = useRef<HTMLButtonElement>(null);
  // <DynamicComponent ref={wrongRef1} label="my label" /> 
  // 报错:传入label时ref仅支持HTMLLabelElement类型

  // const wrongRef2 = useRef<HTMLLabelElement>(null);
  // <DynamicComponent ref={wrongRef2} /> 
  // 报错:未传入label时ref仅支持HTMLButtonElement类型

  return (
    <>
      <DynamicComponent ref={btnRef} />
      <DynamicComponent ref={labelRef} label="my label" />
    </>
  );
}

实现逻辑说明

  • 用never限制ButtonProps不能传入label属性,和必须传label的LabelProps形成互斥的联合类型,避免两种属性同时存在的非法场景
  • 两层函数重载分别对应两种传参场景,直接把ref类型和当前的Props类型绑定,调用组件时TS会自动匹配对应的重载签名
  • 内部实现的forwardRef用联合类型兼容两种场景,因为已经通过if判断了label的存在性,类型断言是安全的

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 15:24:00