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

React Hook Form多步表单单选框首次提交返回null问题排查

问题分析与解决方案

问题核心

使用react-hook-form构建的多步表单中,单选按钮首次提交时值为null,二次提交才正常;仅数组最后一个选项("three")首次提交正常。问题大概率出在自定义点击事件干扰了单选按钮的默认选中逻辑,导致react-hook-form无法及时捕获选中值。


解决方案

方案1:移除自定义点击事件,利用label默认行为

<label>通过htmlFor已关联单选按钮,点击label内任意内容都会自动选中对应radio,无需额外给<p>绑定点击事件。若需实现选中态样式,直接通过react-hook-form的watchAPI获取当前值即可。

修改第一步表单代码:

// 先通过watch获取当前选中值
const singleType = watch('singleType');

{Type.map((item, index) => (
  <label key={index} htmlFor={`Type${index}`}>
    <input
      {...register('singleType', { required: true })}
      type="radio"
      id={`Type${index}`}
      value={item}
    />
    {/* 通过watch值控制选中样式 */}
    <p className={singleType === item ? 'active-class' : ''}>
      {item}
    </p>
  </label>
))}

方案2:修复自定义点击事件,确保radio值被捕获

若必须保留handleTypeClick函数,需在函数内手动触发radio的change事件,让react-hook-form同步捕获值:

const handleTypeClick = (index) => {
  const radioEl = document.getElementById(`Type${index}`);
  if (radioEl) {
    radioEl.checked = true;
    // 手动触发change事件,同步表单值
    radioEl.dispatchEvent(new Event('change'));
  }
  // 其他业务逻辑...
};

方案3:检查useForm初始化配置

确保useForm的默认值设置不会干扰单选按钮的选中逻辑:

const methods = useForm({
  defaultValues: {
    singleType: '' // 不设置默认选中项,让用户手动选择
  }
});

验证步骤

  1. 点击任意单选按钮后,通过watch('singleType')实时打印值,确认值是否正确更新;
  2. 提交时检查handleStateClick中的data参数,确认是否同步获取到最新值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 10:30:01