javascript - 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!
解决方案
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!
推荐阅读
- javascript - 有没有办法使用 JavaScript 检测浏览器窗口从哪一侧缩小/调整大小?
- javascript - 无法在反应中取消 AWS 放大的 REST(POST)请求
- html - 在不影响其他元素的情况下动态更改 div 之间的页面内容
- c# - 如何在 Android 和 iOS 中使用 xamarin 获取时区
- tensorflow - 神经网络不使用二元交叉熵进行训练
- c++ - 为什么我的缓冲区的输出没有打印出来?
- python - ValueError:熊猫更新后无法使用多维键进行索引
- laravel - 错误,Lcobucci\JWT\Signer\InvalidKeyProvided:无法解析您的密钥
- java - Split() 无法生成 java.lang.ExceptionInInitializerError 。如何消除此错误?
- java - Spring批处理FlatFileItemReader令牌错误