我用react-hook-form创建了一个表单。它在控制台中正确记录“fullName”和“city”,但不记录单选按钮。使用单选按钮,您会得到结果“null”。
我的代码如下。
import React from 'react'
import './App.css';
import {useForm} from "react-hook-form";
function App() {
const {register, handleSubmit} = useForm();
function onSubmitButton(data) {
console.log(data)
}
return (
<>
<h1>Order weather</h1>
<form onSubmit={handleSubmit(onSubmitButton)}>
<input
{...register("fullName")}
type="text"
name="fullName"
placeholder="Name and surname"
id="name"
/>
<input
{...register("city")}
type="text"
name="city"
placeholder="City"
id="city"
/>
<p>I would like to:</p>
<label htmlFor="field-rain">
<input
{...register("rain")}
type="radio"
name="weather"
value="rain"
id="field-rain"
/>
Rain
</label>
<label htmlFor="field-wind">
<input
{...register("wind")}
type="radio"
name="weather"
value="wind"
id="field-wind"
/>
Lots of wind
</label>
<label htmlFor="field-sun">
<input
{...register("sun")}
type="radio"
name="weather"
value="sun"
id="field-sun"
/>
Sunny
</label>
<button type="submit">
Send
</button>
</form>
</>
);
}
export default App;
当我关闭时name= "weather"
我检查了它确实放在控制台中的按钮,但它不应该允许我同时检查所有按钮。任何人都知道如何确保我可以获取控制台中签入的内容?
由于雨、风、太阳应该分配给相同的值,我们需要将相同的参数传递给注册函数,如下所示
function App() {
const {register, handleSubmit} = useForm();
function onSubmitButton(data) {
console.log(data)
}
return (
<>
<h1>Order weather</h1>
<form onSubmit={handleSubmit(onSubmitButton)}>
<input
{...register("fullName")}
type="text"
placeholder="Name and surname"
id="name"
/>
<input
{...register("city")}
type="text"
placeholder="City"
id="city"
/>
<p>I would like to:</p>
<label htmlFor="field-rain">
<input
{...register("weather")}
type="radio"
value="rain"
id="field-rain"
/>
Rain
</label>
<label htmlFor="field-wind">
<input
{...register("weather")}
type="radio"
value="wind"
id="field-wind"
/>
Lots of wind
</label>
<label htmlFor="field-sun">
<input
{...register("weather")}
type="radio"
value="sun"
id="field-sun"
/>
Sunny
</label>
<button type="submit">
Send
</button>
</form>
</>
);
}
export default App;
我希望这能解决这个问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)