首页 > 解决方案 > Why do these uncontrolled radio inputs require two clicks to be selected?

问题描述

I have a radio group in a form which uses react-hook-form's useForm hook. Note that the form's mode is set to onChange instead of onSubmit. Both the radio inputs in the group require two clicks to be checked off but, their values are being properly set in one click.

This short GIF will explain my problem better: https://imgur.com/a/Pdivd3p

Radio group:

<div>
  <label>Radio group label...</label>
  <div>
    <div>
      <label>
        <span>Yes</span>
          <input
            name="radioName"
            type="radio"
            value={true}
            ref={register}
          />
      </label>
    </div>
    <div>
      <label>
        <span>No</span>
          <input
            name="radioName"
            type="radio"
            value={false}
            ref={register}
          />
      </label>
    </div>
  </div>
</div>

This is the onChange method for the entire form (the console.logs in the GIF are from here):

const handleFormChange = data => {
    console.log(data.radioName)
}

What should I do to have the radio inputs get checked off in one click? Any help is greatly appreciated!

标签: javascriptreactjsinputreact-hooksradio-group

解决方案


After trying a bunch of possible solutions and testing on other devices, it appears the issue was simply the onChange handler for the whole form. The form code looked something like this:

// handleSubmit is provided by react-hook-form
// handleFormChange prints the value of each form input
<form onChange={handleSubmit(handleFormChange)}>
  {...}
  // radio buttons were here
</form>

The onChange handler was working perfectly but inadvertently causing the radio clicking issue. After removing the onChange, this issue was resolved.

Now, I'm using react-hook-form's watch() method to gather all the values from the form inputs using the following useEffect hook:

let data = watch()

useEffect(() => {
  console.log(data)
}, [data])

This is essentially providing the same result as the onChange handler without the radio button double clicking issue!


推荐阅读