react-hook-form封装Radio时TS报无Group属性,如何绑定Radio.Group
报错根本原因
- 通过
React.forwardRef创建的Radio组件,返回值的静态类型为ForwardRefExoticComponent<InputProps & RefAttributes<HTMLInputElement>>,该类型的定义中不包含.Group静态成员。手动为Radio组件挂载.Group属性时,TypeScript的静态类型检查无法识别未预先声明的成员,因此抛出TS2339报错。 - 原有react-hook-form适配逻辑存在偏差:为Radio.Group错误传入
checked属性、错把单选项的label作为Group的内容渲染,没有正确将Controller返回的字段透传给antd原生组件。
正确适配方案
- 为Radio组件补充静态类型定义,将.Group成员的类型预先声明到组件的整体类型上,让TypeScript可以正常识别该属性。
- 调整Group组件的绑定逻辑:antd的Radio.Group是容器型组件,直接透传Controller返回的
value、onChange、name字段即可,不需要额外手动维护选中状态。 - 移除冗余属性绑定:不需要手动为antd Radio组件传入
checked,react-hook-form的field返回值已经包含了组件需要的全部交互属性,直接透传即可完成兼容。
完整参考实现代码
import React from 'react'; import { Radio as $Radio } from 'antd'; import type { RadioGroupProps } from 'antd/lib/radio'; import { Controller, useFormContext } from 'react-hook-form'; import type { InputProps } from './types'; // 为Radio组件补充Group静态属性的类型声明 type RadioComponentWithGroup = React.ForwardRefExoticComponent< InputProps & React.RefAttributes<HTMLInputElement> > & { Group: React.FC< Omit<RadioGroupProps, 'value' | 'onChange'> & { name: string; control?: Parameters<typeof Controller>[0]['control']; } >; }; // 基础单选项Radio实现 const Radio = React.forwardRef<HTMLInputElement, InputProps>((props, ref) => { const { id, name, label, control, ...rest } = props; const formCtx = useFormContext(); const usedControl = control ?? formCtx.control; return ( <Controller name={name} control={usedControl} render={({ field }) => ( <$Radio {...rest} {...field} id={id} ref={ref} className="radio" > {label} </$Radio> )} /> ); }) as RadioComponentWithGroup; // Radio.Group适配实现 Radio.Group = (props) => { const { name, control, children, ...rest } = props; const formCtx = useFormContext(); const usedControl = control ?? formCtx.control; return ( <Controller name={name} control={usedControl} render={({ field }) => ( <$Radio.Group {...rest} {...field} className="radio-group" > {children} </$Radio.Group> )} /> ); }; export default Radio;
补充使用说明
- 按照上述方式为组件做类型断言后,TS可正常识别
Radio.Group成员,不会再抛出属性不存在的报错。 - 实现中接入了
useFormContext,如果页面已经全局初始化过Form实例,不需要在每个Radio、Group节点上重复传入control属性,减少冗余代码。 - 实际使用时直接将自定义Radio组件作为Group的子节点传入即可,不需要在Group内部重复实现选项逻辑。
内容的提问来源于stack exchange,提问作者Serenity
相关产品推荐
相关产品推荐

