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

React Hook Form单选按钮首次点击无效,值为null问题求助

问题解决:React Hook Form单选按钮首次点击不生效

问题原因

  1. DOM结构错误:你的代码里存在未配对的</h3>标签,浏览器自动修正DOM结构时会干扰单选按钮的点击事件绑定,导致首次点击时事件未正确触发到input元素,无法完成选中操作。
  2. 重复注册的潜在冲突:虽然React Hook Form允许对同一字段的多个单选按钮调用register,但重复的注册逻辑可能引发事件处理冲突,导致首次点击时状态未被正确同步。

修复后的代码

<div>
  <p>Radio Button</p>
  <span className="form__error">
    {errors.types && 'This is a required field'}
  </span>
  <div>
    <label htmlFor='a'>
      <input
        {...register('types', { required: true })}
        id='a'
        type="radio"
        value="a"
      />
      a
    </label>
    <label htmlFor='b'>
      <input
        {...register('types', { required: true })}
        id='b'
        type="radio"
        value='b'
      />
      b
    </label>
    <label htmlFor='c'>
      <input
        {...register('types', { required: true })}
        id='c'
        type="radio"
        value='c'
      />
      c
    </label>
    <label htmlFor='d'>
      <input
        {...register('types', { required: true })}
        id='d'
        type="radio"
        value='d'
      />
      d
    </label>
  </div>
</div>

优化建议

  • 提取注册逻辑,避免重复代码:
    // 组件内提前定义
    const typesRegister = register('types', { required: true });
    
    // 每个单选按钮直接复用
    <input {...typesRegister} id='a' type="radio" value="a" />
    
  • 如果问题仍存在,尝试用Controller组件受控管理单选组:
    <Controller
      name="types"
      control={control}
      rules={{ required: true }}
      render={({ field }) => (
        <div>
          <label htmlFor='a'>
            <input {...field} id='a' type="radio" value="a" />
            a
          </label>
          <label htmlFor='b'>
            <input {...field} id='b' type="radio" value='b' />
            b
          </label>
          {/* 其他选项同理 */}
        </div>
      )}
    />
    

内容的提问来源于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.16 17:07:21