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

React Hook Form:带自定义输入的单选框提交数据合并问题

实现单选框组+自定义输入合并提交字段的方案

完全可行,以下两种常用方案可以满足你的需求:

方案一:实时联动字段值(推荐)

不将自定义输入框注册为独立表单字段,而是通过状态维护输入值,并实时同步到radioWithCustom字段,确保表单始终只有该字段存在。

import { useForm, useEffect } from 'react-hook-form';
import { useState } from 'react';

function CustomRadioForm() {
  const { register, watch, setValue, handleSubmit } = useForm({
    defaultValues: {
      radioWithCustom: 'option1' // 默认选中第一个常规选项
    }
  });
  const [customInputVal, setCustomInputVal] = useState('');
  const selectedRadio = watch('radioWithCustom');

  // 监听单选框切换,同步自定义输入值到目标字段
  useEffect(() => {
    if (selectedRadio === 'custom') {
      setValue('radioWithCustom', customInputVal);
    }
  }, [selectedRadio, customInputVal, setValue]);

  // 自定义输入框变化时同步值
  const handleCustomInput = (e) => {
    const val = e.target.value;
    setCustomInputVal(val);
    if (selectedRadio === 'custom') {
      setValue('radioWithCustom', val);
    }
  };

  const onSubmit = (formData) => {
    // 提交时仅包含radioWithCustom字段,值为常规选项或自定义内容
    console.log(formData);
    // 执行接口提交逻辑
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      {/* 常规单选选项 */}
      <div>
        <input type="radio" value="option1" {...register('radioWithCustom')} />
        <label>选项1</label>
      </div>
      <div>
        <input type="radio" value="option2" {...register('radioWithCustom')} />
        <label>选项2</label>
      </div>

      {/* 自定义选项 */}
      <div>
        <input type="radio" value="custom" {...register('radioWithCustom')} />
        <label>自定义输入</label>
        <input
          type="text"
          disabled={selectedRadio !== 'custom'}
          value={customInputVal}
          onChange={handleCustomInput}
          placeholder="请输入自定义内容"
        />
      </div>

      <button type="submit">提交表单</button>
    </form>
  );
}

方案二:提交前合并字段(兼容现有代码)

如果不想修改现有字段注册逻辑,可以在提交时手动处理数据,将自定义输入值合并到radioWithCustom后删除多余字段:

const { register, handleSubmit } = useForm({
  defaultValues: {
    radioWithCustom: 'option1',
    customText: ''
  }
});

const onSubmit = (rawData) => {
  const submitData = { ...rawData };
  // 判断是否选中自定义选项,将customText的值赋值给radioWithCustom
  if (submitData.radioWithCustom === 'custom' || submitData.radioWithCustom === null) {
    submitData.radioWithCustom = submitData.customText;
  }
  // 删除多余的customText字段
  delete submitData.customText;
  
  console.log(submitData); // 仅保留radioWithCustom字段
  // 执行接口提交逻辑
};

注意事项

  • 方案一更简洁,避免表单冗余字段,推荐使用;
  • 若需要对自定义输入做校验,可在handleCustomInput中添加校验逻辑,或使用useForm的trigger方法触发校验;
  • 确保自定义单选选项的value(如示例中的custom)与常规选项值区分开,便于判断逻辑执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 04:10:55