如何在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
相关产品推荐
相关产品推荐

