使用react-hook-form实现表单提交后显示段落提示并清空表单
Solution: Replace Alert with Inline Message & Clear Form on Submit
Got it, let's tweak your Form component to show an inline success message instead of an alert, and clear the form fields after submission. Here's the updated code with explanations:
import React, { useState } from "react"; import { useForm } from "react-hook-form"; // Assuming Title is a component you've defined elsewhere import Title from "./Title"; const Form = ({ title }) => { // State to manage success message visibility and content const [successMessage, setSuccessMessage] = useState(""); // Destructure `reset` from useForm to clear form fields const { register, handleSubmit, errors, reset } = useForm(); const onSubmit = (data) => { // No need for e.preventDefault() — handleSubmit handles this automatically console.log(data); // Set the success message with the user's name setSuccessMessage(`Thank you ${data.name} for your message!`); // Reset all form fields to empty reset(); }; return ( <div className="formContainer"> <Title title="Lets stay in touch" /> <div className="form"> <form onSubmit={handleSubmit(onSubmit)}> <div className="form__row"> <input className={`inputForm ${errors.name ? "inputFormError" : ""}`} name="name" type="text" placeholder="name" ref={register({ required: true })} /> <input className={`inputForm ${errors.surname ? "inputFormError" : ""}`} name="surname" type="text" placeholder="surname" ref={register({ required: true })} /> </div> <div> <textarea className={`inputForm areaForm ${errors.message ? "inputFormError" : ""}`} name="message" placeholder="Your message" ref={register({ required: true })} ></textarea> </div> <div> <button className="form__formButton" type="submit"> Send </button> </div> </form> {/* Conditionally render success message when it exists */} {successMessage && ( <p className="form__successMessage">{successMessage}</p> )} </div> </div> ); }; export default Form;
Key Changes Breakdown:
- Success Message State: We added
useStateto track when to show the success message and what it should say. This lets us display a clean inline message instead of an intrusive alert. - Reset Form Fields: The
resetmethod fromreact-hook-formis the easiest way to clear all registered form fields in one go — no need to manually set each input to empty. - Conditional Rendering: The success paragraph only appears when
successMessagehas content, so it stays hidden until the form is submitted successfully. - Removed Redundant
e.preventDefault():handleSubmitfromreact-hook-formalready prevents the default form submission behavior, so we can safely remove that line.
Optional Styling Tip:
Add some CSS to make the success message stand out:
.form__successMessage { color: #27ae60; margin-top: 1rem; font-weight: 500; padding: 0.5rem; border-left: 3px solid #27ae60; }
内容的提问来源于stack exchange,提问作者Nta
相关产品推荐
相关产品推荐

