You need to enable JavaScript to run this app. 如何在React Hook Form v7中正确使用Radio Button单选按钮?
优惠活动
大模型
产品
解决方案
定价
更多

如何在React Hook Form v7中正确使用Radio Button单选按钮?

问题根因

Ionic的IonRadioGroup属于框架封装的自定义组件,不支持直接绑定React Hook Form的register方法(该方法仅适配原生表单元素的事件逻辑),需要用Controller组件做适配,同时你当前的校验规则也漏了单选字段的校验。

具体修改步骤

1. 新增依赖导入

从react-hook-form中引入Controller组件:

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

2. 补全Yup校验规则

给validationSchema添加type字段的必填校验:

const validationSchema = yup.object().shape({
  type: yup.string().required("请选择用户类型"),
  firstName: yup.string().required("First name is required"),
  lastName: yup.string().required("Last name is required"),  
});

3. 替换单选组的注册逻辑

把原来直接用register绑定的IonRadioGroup改成用Controller包裹,同时从useForm的返回值中解构出control参数:

// useForm返回值新增control解构
const {
  register,
  handleSubmit,
  formState: { errors },
  control,
} = useForm({
  mode: "onChange",
  resolver: yupResolver(validationSchema),
});

单选组件部分修改为:

<Controller
  control={control}
  name="type"
  render={({ field: { onChange, value } }) => (
    <IonRadioGroup value={value} onIonChange={e => onChange(e.detail.value)}>
      {/* 原有IonItem、IonRadio代码保持不变 */}
      <IonItem>
        <IonLabel>Type 2</IonLabel>
        <IonRadio value="2" slot="start" />
      </IonItem>
      <IonItem>
        <IonLabel>Type 4</IonLabel>
        <IonRadio slot="start" value="4" />
      </IonItem>
      <IonItem>
        <IonLabel>Type 6</IonLabel>
        <IonRadio slot="start" value="6" />
      </IonItem>
    </IonRadioGroup>
  )}
/>

4. 优化onSubmit逻辑

handleSubmit会自动把所有表单值作为参数传入回调,不需要手动调用getValues获取:

const onSubmit= (data) => {
  // 这里的data已经包含type、firstName、lastName三个字段
  axios
    .post("/add-user", data)
    .then((response) => {
      return response.data;
    })
    .catch((error) => {
      setMessage(`You are already registered`);
      setIserror(true);
    });
};

5. 冗余代码清理

你声明的type、firstName、lastName三个useState完全没有用到,React Hook Form会自行管理表单状态,直接删除即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 04:45:03