简体   繁体   English

React-hook-form 的“重置”工作正常,提交后输入字段仍未清空

[英]React-hook-form's 'reset' is working properly, input fields are still not emptying after submit

I've tried using the "reset" function form react-hook-form but after submitting the input fields are not emptying.我尝试使用“reset” function 表单 react-hook-form 但在提交输入字段后没有清空。 I don't know why exactly, I"m sure I"m missing something but cannot find what.我不知道究竟是为什么,我确定我错过了一些东西,但找不到什么。

Here's my code:这是我的代码:

const Form = () => {
  const [values, setValues] = useState({
    email: "",
    name: "",
    subject: "",
    description: "",
  });

  const { register, handleSubmit, reset, errors } = useForm();


  toastr.options = {"positionClass": "toast-top-right","progressBar": true,}
  const onSubmit = (values, e) => {
    
    const { email, name, subject, description } = values;
    axios.post("http://localhost:8080/sendme", {
      email,
      name,
      subject,
      text: description,
    });
   
    e.target.reset();
    toastr.success('Message was sent successfully!');
   
  };

  const handleChange = (e) => {
    const { name, value } = e.target;
    setValues({
      ...values,
      [name]: value,
    });
    
  };


  return (
    <div>
      <form onSubmit={handleSubmit(onSubmit)} noValidate>
        <div className="inputField">
          <input
            className={`${errors.email && "inputError"}`}
            name="email"
            type="email"
            ref={register({ required: true, pattern: /^\S+@\S+$/i })}
            placeholder="Your email *"
            value={values.email}
            onChange={handleChange}
          />
          <ErrorMessage error={errors.email} />
        </div>
        <div className="inputField">
          <input
            className={`${errors.name && "inputError"}`}
            name="name"
            type="text"
            placeholder="Your name *"
            ref={register({ required: true })}
            value={values.name}
            onChange={handleChange}
          />
          <ErrorMessage error={errors.name} />
        </div>
        <div className="inputField">
          <input
            className={`${errors.subject && "inputError"}`}
            name="subject"
            type="text"
            placeholder="Subject *"
            ref={register({ required: true })}
            value={values.subject}
            onChange={handleChange}
          />
          <ErrorMessage error={errors.subject} />
        </div>
        <div className="inputField">
          <p className="reqTxt"> * = Required</p>
          <textarea
            className={`${errors.description && "inputError"}`}
            name="description"
            placeholder="Type your message here *"
            ref={register({ required: true, minLength: 15 })}
            value={values.description}
            onChange={handleChange}
            rows="15"
            cols="80"
          ></textarea>
          <ErrorMessage error={errors.description} />
        </div>

        <button className="btn" onClick={reset} type="submit">
          Send message
        </button>
      </form>
    </div>
  );
};

I've imported the reset and used it with onClick but it doesn't seem to work.我已导入重置并将其与 onClick 一起使用,但它似乎不起作用。 How should I fix this?我应该如何解决这个问题?

When you using react-hook-form, you are most likely can skip using useState:当您使用 react-hook-form 时,您很可能可以跳过使用 useState:

https://react-hook-form.com/get-started https://react-hook-form.com/get-started

Here is a quick example at the get started page:这是入门页面上的一个简单示例:

import React from "react";
import { useForm } from "react-hook-form";

export default function App() {
  const { register, handleSubmit, watch, errors } = useForm();
  const onSubmit = data => console.log(data);

  console.log(watch("example")); // watch input value by passing the name of it

  return (
    {/* "handleSubmit" will validate your inputs before invoking "onSubmit" */}
    <form onSubmit={handleSubmit(onSubmit)}>
    {/* register your input into the hook by invoking the "register" function */}
      <input name="example" defaultValue="test" ref={register} />
      
      {/* include validation with required or other standard HTML validation rules */}
      <input name="exampleRequired" ref={register({ required: true })} />
      {/* errors will return when field validation fails  */}
      {errors.exampleRequired && <span>This field is required</span>}
      
      <input type="submit" />
    </form>
  );
}

Make logic, whenever you want to reset your input.制定逻辑,只要你想重置你的输入。 just invoke the reset method只需调用reset方法

import React from "react"
import { useForm } from "react-hook-form"

export default function App() {
  const { register, handleSubmit, errors, reset } = useForm()
  const onSubmit = data => {
    console.log(data)
    reset()
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <label htmlFor="firstName">First name</label>
      <input
        id="firstName"
        type="text"
        aria-invalid={errors.firstName ? "true" : "false"}
        name="firstName"
        ref={register({ required: true })}
      />

      <input type="submit" />
    </form>
  )
}

cheer you!为你加油!

try this:尝试这个:

const submit = (data, e)=>{
      console.log(data);
      e.target.reset();
}

use the following code to reset the input fields使用以下代码重置输入字段

e.target[0].value = ''; // email
e.target[1].value = '';  //name
e.target[2].value = '';  //subject 
e.target[3].value = '';  //description

You can use您可以使用

reset({});

This piece of code reset all your form这段代码重置了你所有的表单

If you want to reset only specific fields, and keep the rest unchanged (to avoid having to retype everything), you can specify like this for instance:如果您只想重置特定字段,并保持 rest 不变(以避免重新输入所有内容),您可以这样指定,例如:

    reset({currentPassword: ""});

Hell no,一定不行,

To reset all values just use reset() method.要重置所有值,只需使用 reset() 方法。

Documentation文档

In the other hand, I see that this method doesn't work on Edge, and FF, but it works on chrome perfectly.另一方面,我看到这种方法在 Edge 和 FF 上不起作用,但它在 chrome 上完美运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM