在reactjs钩子中提交后如何重置表单

时间:2020-07-14 22:52:39

标签: javascript reactjs react-hooks

这是我第一次使用钩子,我不知道如何在提交后清除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>
  );
}

预先感谢

//////////

here is the error when I use form.reset()

2 个答案:

答案 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]
  };