这是我第一次使用钩子,我不知道如何在提交后清除form.reset()输入字段
import { useForm } from "react-hook-form";
import....
export default function AddUser() {
const URL = "http://localhost:3000/AddUser";
const { register, handleSubmit, errors } = useForm();
const onSubmit = (data) => {
if (data) {
axios.post(URL, data);
}
form.reset()
};
这是退货部分
return (
<form onSubmit={handleSubmit(onSubmit)} noValidate>
<div className="container">
<input type="text" name="name" placeholder="Name" ref={register({required: true})}/>
<input type="radio" name="gender" value="male" ref={register({ required: true })}/>:Male
<input type="radio" name="gender" value="female" ref={register({ required: true })}/:Female
<button type="submit" className="btn "> add</button>
</div>
</form>
);
}
预先感谢
//////////
答案 0 :(得分:4)
您需要从reset
钩子导入useForm()
才能在标签之外使用它。
所以
const { register, handleSubmit, errors, reset } = useForm();
然后使用您的提交功能
const onSubmit = (data) => {
if (data) {
axios.post(URL, data);
}
reset({})
};
应该遵循这些原则。
答案 1 :(得分:2)
您需要设置一个默认状态,以在单击时进行设置,这样您的组件将在每次提交时重置。但是,如果您想阻止默认设置,则必须在event.preventDefault();
函数中设置onSubmit
import { useForm, useState } from "react-hook-form";
import....
export default function AddUser() {
const [formState, setFormState] = useState({})
const URL = "http://localhost:3000/AddUser";
const { register, handleSubmit, errors } = useForm();
const onSubmit = (data) => {
if (data) {
setFormState(data)
axios.post(URL, formState);
}
form.reset()[![enter image description here][1]][1]
};