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

在Chakra UI Radio Group中使用React Hook Form register报错求助

修复Chakra UI RadioGroup与React Hook Form register不兼容的问题

问题根源

Chakra UI的RadioGroup属于受控组件,它的onChange回调直接接收选中的字符串值(比如"MALE"),但React Hook Form的register方法返回的onChange函数期望接收的是事件对象,直接解构或单独传递都会因为参数类型不匹配引发报错——这也是为什么register在Input、Select这类组件能正常工作的原因,它们的onChange都是接收事件对象。

解决方案:用Controller组件适配

React Hook Form提供了Controller组件,专门用来对接这类非标准的受控组件,帮我们完成参数格式的转换。

步骤1:导入Controller

import { Controller } from "react-hook-form";

步骤2:重构RadioGroup代码

确保你已经从useForm中获取了control和errors对象:

const { control, formState: { errors } } = useForm({
  defaultValues: {
    gender: "" // 可根据需求设置默认选中值
  }
});

然后替换原来的RadioGroup部分:

<FormControl as="fieldset" isInvalid={!!errors.gender}>
  <Controller
    name="gender"
    control={control}
    rules={{ required: "请选择性别" }} // 自定义校验规则,和register用法一致
    render={({ field }) => (
      <RadioGroup
        value={field.value}
        onChange={field.onChange}
      >
        <HStack spacing="24px">
          <Radio value="MALE">Male</Radio>
          <Radio value="FEMALE">Female</Radio>
        </HStack>
      </RadioGroup>
    )}
  />
  {errors.gender && (
    <FormErrorMessage>{errors.gender?.message}</FormErrorMessage>
  )}
</FormControl>

代码说明

  • Controller的render函数返回的field对象已经做了适配,其中的onChange可以直接接收RadioGroup传递的选中值,完美匹配Chakra组件的参数要求。
  • value绑定field.value,保证表单值和RadioGroup的选中状态实时同步。
  • 校验规则通过rules参数配置,逻辑和使用register时完全一致。

内容的提问来源于stack exchange,提问作者Muhammad Mubashirullah Durrani

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 05:07:32