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

如何在React TypeScript中动态获取forwardRef子组件的Ref属性

动态获取forwardRef组件的Ref属性类型

可以通过TypeScript条件类型,直接从typeof Child中提取forwardRef定义的Ref属性类型,无需导出子组件的RefProps接口。

方法一:从ForwardRef组件类型直接推断

利用React.ForwardRefExoticComponent的类型结构,通过条件类型提取Ref的泛型参数:

// 提取Child组件的Ref属性类型
type ChildRefType = typeof Child extends React.ForwardRefExoticComponent<
  React.PropsWithRef<infer _Props> & React.RefAttributes<infer RefType>
> ? RefType : never;

const Parent = () => {
  // 将提取的类型作为useRef的泛型参数
  const childRef = useRef<ChildRefType>(null);

  return (
    <Child ref={childRef} prop1="test" />
  );
};

方法二:通过ComponentPropsWithRef间接提取

借助React.ComponentPropsWithRef获取包含ref的组件props类型,再从中推断出Ref的实际类型:

// 从组件props的ref属性中提取目标类型
type ChildRefType = NonNullable<React.ComponentPropsWithRef<typeof Child>['ref']> extends React.Ref<infer RefType> 
  ? RefType 
  : never;

const Parent = () => {
  const childRef = useRef<ChildRefType>(null);

  return (
    <Child ref={childRef} prop1="test" />
  );
};

两种方案都能实现动态获取子组件Ref属性类型的需求,无需在父组件中导入子组件内部的RefProps接口。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 17:53:30