【发布时间】:2021-08-10 01:55:57
【问题描述】:
我用 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" 并检查按钮时,它确实将它放在控制台中,但它不应该允许我同时检查所有按钮。任何人都知道如何确保我可以将检查到控制台中的内容?
【问题讨论】:
-
如果您在
label-元素内使用input-字段,则无需指定htmlFor属性(或id字段上的id属性就此而言)。
标签: reactjs forms radio react-hook-form