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

React Hook Form实现单选按钮触发字段动态必填需求咨询

React Hook Form 动态控制字段必填状态示例

直接给你完整实现示例,核心是用watch API监听单选按钮的选中值,动态设置目标字段的必填规则:

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

function DynamicRequiredForm() {
  const { register, watch, handleSubmit, formState: { errors } } = useForm({
    defaultValues: {
      selectedOption: "",
      targetField: ""
    }
  });

  // 实时监听单选按钮的选中值
  const selectedOption = watch("selectedOption");

  // 动态生成的单选选项数据(可替换为接口返回的动态数据)
  const radioOptions = [
    { value: "option1", label: "选项1" },
    { value: "option2", label: "选项2(选此需填写目标字段)" },
    { value: "option3", label: "选项3" }
  ];

  const onSubmit = (data) => {
    console.log("提交的表单数据:", data);
    // 这里添加你的表单提交逻辑
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <div>
        <label>选择选项:</label>
        {radioOptions.map((option) => (
          <div key={option.value}>
            <input
              type="radio"
              {...register("selectedOption", { required: "请选择一个选项" })}
              value={option.value}
            />
            <span>{option.label}</span>
          </div>
        ))}
        {errors.selectedOption && <p style={{ color: "red" }}>{errors.selectedOption.message}</p>}
      </div>

      <div style={{ marginTop: "1rem" }}>
        <label>目标字段:</label>
        <input
          type="text"
          {...register("targetField", {
            // 当选中option2时,该字段变为必填项
            required: selectedOption === "option2" ? "请填写目标字段" : false
          })}
        />
        {errors.targetField && <p style={{ color: "red" }}>{errors.targetField.message}</p>}
      </div>

      <button type="submit" style={{ marginTop: "1rem" }}>提交</button>
    </form>
  );
}

export default DynamicRequiredForm;

关键逻辑说明:

  • 监听选中值:watch("selectedOption")会实时同步单选按钮的选中状态,用户切换选项时该值自动更新。
  • 动态必填规则:在目标字段的register配置中,通过判断选中值是否为特定值(示例中为option2),动态设置required规则,同时支持自定义错误提示文本。
  • 动态渲染单选选项:通过map循环遍历选项数组生成单选按钮,数组内容可直接替换为接口返回的动态数据。
  • 错误提示:借助formState.errors获取字段校验错误,实时展示给用户。

如果使用Ant Design、MUI等UI组件库的单选组件,只需将原生input替换为对应组件,配合Controller组件封装即可,核心的监听和动态必填逻辑保持一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 20:27:30