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

如何在React Hook Form提交数据到Firebase后清空表单字段?

解决React Hook Form提交后清空表单字段的问题

要实现Firebase数据提交成功后清空表单,只需利用React Hook Form提供的reset方法,操作步骤如下:

1. 解构获取reset方法

从useForm钩子中解构出reset函数,修改原代码的useForm调用部分:

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

2. 提交成功后调用reset

在onSubmit函数中,确保Firebase请求完成后调用reset(),即可清空所有表单字段:

const onSubmit = async (data) => {
    console.log(data);
    // 发送数据到Firebase
    const responseRaw = await fetch(
      "https://test1-5022f-default-rtdb.firebaseio.com/reactformData.json",
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify(data)
      }
    );
    const response = await responseRaw.json(); // 加上await确保请求完成
    reset(); // 清空表单字段
  };

修改后的完整组件代码

import React from "react";
import "./App.css";
import { useForm } from "react-hook-form";
import classNames from "classnames";

function App() {
  // 新增reset方法解构
  const { register, handleSubmit, formState: { errors }, reset } = useForm();

  const onSubmit = async (data) => {
    console.log(data);
    // 发送数据到Firebase
    const responseRaw = await fetch(
      "https://test1-5022f-default-rtdb.firebaseio.com/reactformData.json",
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify(data)
      }
    );
    const response = await responseRaw.json();
    reset(); // 提交后清空表单
  };

  return (
    <form name="Registration_form" id="Form" action="" method="POST" onSubmit={handleSubmit(onSubmit)}>
          
          <div className="form-group my-3">
            <label htmlFor="name">Name:</label>
           
            <input 
              type="text" 
              name="Name" 
              id="Name"
              className={classNames("form-control",{"is-invalid":errors.Name,})}  
              autoComplete="off" 
              {...register('Name', 
              { required: true,
                maxLength: 15,
                pattern: /^[A-Za-z]+$/
              
              })
              }

              />

            <span id="name" className="text-danger fw-bold">{errors.Name?.type === "required"  && "This field is required"}</span>

            <span id="name" className="text-danger fw-bold">{errors.Name?.type ==="maxLength" && "Length Should be less then 15"}</span>

            <span id="name" className="text-danger fw-bold">{errors.Name?.type === "pattern"  && "Digits are not allow"}</span>

          </div>

          <div className="form-group my-3">
            <label htmlFor="email">Email: </label>
            
            <input 
              type="text" 
              name="email" 
              id="email"
              className={classNames("form-control",{"is-invalid":errors.email,})}  
              placeholder="email@example.com" 
              autoComplete="off" 
              {...register('email', 
              { 
                required: true,
                pattern:/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/, 
              
              })
              }
            
              />

              <span id="mail" className="text-danger fw-bold">{errors.email?.type === "required"  && "Email is required"}</span>

              <span id="mail" className="text-danger fw-bold">{errors.email?.type === "pattern"  &&"Invalid format"}</span>

           
          </div>
          <input type="submit" id="submit" value="submit"  className="btn btn-success my-3" />
        </form>
  );
}

export default App;

原理说明

reset是React Hook Form内置的API,调用后会将所有通过register注册的表单字段值重置为空,同时清除表单的错误状态,完美匹配提交后清空表单的需求。

内容的提问来源于stack exchange,提问作者Shaheer Ahmed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 13:24:21