简体   繁体   English

如何通过按下按钮重置 React 组件中的表单值?

[英]How can I reset the form values in a React component with a button press?

I'm using the below Contact component to handle a simple form in react to send an email. I want the sendEmail function to also clear the form fields but I've tried referencing them through form.current and that doesnt seem to be working.我正在使用下面的联系人组件来处理一个简单的表单,以发送 email。我希望 sendEmail function 也清除表单字段,但我已经尝试通过 form.current 引用它们,但似乎没有用。 Is there another way I need to reference them to set the values?还有其他方法我需要引用它们来设置值吗? I also tried e.target.reset() and it didn't seem to do anything.我也试过e.target.reset()但它似乎没有做任何事情。

import React, { useRef } from 'react';
import emailjs from 'emailjs-com';

const Contact = () => {
  const form = useRef();

  const sendEmail = (e) => {
    e.preventDefault();

    const serviceId='...';
    const templateId='...';
    const userId='...';

    emailjs.sendForm(serviceId, templateId, form.current, userId)
      .then((result) => {
          console.log(result.text);
      }, (error) => {
          console.log(error.text);
      });
    };

    return (
        <form onSubmit={sendEmail} ref={form}>
            <div className="field half first">
                <label htmlFor="name">Name</label>
                <input type="text" name="fromName" id="name"/>
            </div>
            <div className="field half">
                <label htmlFor="email">Email</label>
                <input type="text" name="fromEmail" id="email"/>
            </div>
            <div className="field">
                <label htmlFor="message">Message</label>
                <textarea name="message" id="message" rows="4"
                placeholder = "..."></textarea>
            </div>
            <ul className="actions">
                <li>
                    <input type="submit" value="Send Message" className="special"/>
                </li>
            </ul>
        </form>
    );
};

export default Contact

There are so many ways to doing this, basically on how the component has been structured to collect the data.有很多方法可以做到这一点,主要是关于如何构建组件来收集数据。 However, following your pattern of arrangement, why don't you set a boolean variable or something coercible to a boolean value (value initially set to false) that is made aware (ie value changes to true or 'sent') when the email has been successfully sent.但是,按照您的安排模式,为什么不设置 boolean 变量或可强制设置为 8832400701688 值(值最初设置为 false)的东西,当 email 有已成功发送。

import {useState} from "react";
const [emailStatus, setEmailStatus] = useState("Not sent");

Then use the useEffect-hook to re-render the component, whenever the emailStatus variable changes to true or 'sent' and thereby clear-out the form values.然后使用 useEffect-hook 重新渲染组件,只要 emailStatus 变量更改为 true 或“已发送”,从而清除表单值。
Hence, in your function:因此,在您的 function 中:

emailjs.sendForm(serviceId, templateId, form.current, userId)
      .then((result) => {
          .... any other logic
          console.log(result.text);
          setEmailStatus('sent');
          ................
useEffect(() => {
    //clear form fields here
}, [emailStatus]);

return(
     .....
     .....
);

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

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