You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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 useState to 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 reset method from react-hook-form is 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 successMessage has content, so it stays hidden until the form is submitted successfully.
  • Removed Redundant e.preventDefault(): handleSubmit from react-hook-form already 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 21:07:44