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

React登录页div错误提示自动消失及输入触发消失实现方案

React登录页双场景错误提示清除实现方案

完全适配现有代码结构,无需重构原有业务逻辑,仅做增量修改即可实现两个需求:

  • 错误提示展示后定时自动消失
  • 用户在对应输入框输入时关联错误立即清除

具体实现步骤

1. 补充依赖引入

在React的导入项中新增useRef、useEffect两个钩子,用于管理定时器、监听错误状态变化:

import React, { useState, useRef, useEffect } from "react";

2. 新增错误清除核心逻辑

在原有error状态定义的位置,新增定时器实例存储、统一清除方法、自动消失监听逻辑:

// 原有错误状态定义
const [error, setError] = useState({ name: "", message: "" });
// 存储定时器ID,避免内存泄漏、定时器重复叠加
const errorTimer = useRef(null);

// 统一错误清除方法
const clearError = () => {
  setError({ name: "", message: "" });
  if (errorTimer.current) {
    clearTimeout(errorTimer.current);
    errorTimer.current = null;
  }
};

// 监听错误状态,有新错误时启动自动消失倒计时
useEffect(() => {
  if (error.name) {
    // 清除已有定时器,避免多个倒计时叠加
    if (errorTimer.current) clearTimeout(errorTimer.current);
    // 3秒后自动清除错误,时长可按需调整
    errorTimer.current = setTimeout(clearError, 3000);
  }
  // 组件卸载时清除未执行的定时器,防止内存泄漏
  return () => {
    if (errorTimer.current) clearTimeout(errorTimer.current);
  };
}, [error]);

3. 给输入框绑定输入触发清除事件

修改两个输入框的定义,新增onInput事件,用户输入时判断如果当前错误属于该字段,立即清除错误:

{/* 学号输入框 */}
<input 
  type="text" 
  className="input text" 
  onInput={() => error.name === "admission" && clearError()}
/>

{/* 密码输入框 */}
<input 
  type="password" 
  className="input text" 
  onInput={() => error.name === "password" && clearError()}
/>

完整修改后代码

import React, { useState, useRef, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import "./Login.css";
import Intro from "../../Components/Intro/Intro";
import axios from "axios";

const Login = () => {
  const navigate = useNavigate();
  const errorTimer = useRef(null);

  const clearError = () => {
    setError({ name: "", message: "" });
    if (errorTimer.current) {
      clearTimeout(errorTimer.current);
      errorTimer.current = null;
    }
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    var [adm, pass] = document.forms[0];

    if (adm.value) {
      if (pass.value) {
        const cred = {
          identifier: "HSM/001/2021",
          password: pass.value,
        };
        axios
          .post("http://localhost:8000/api/credentials", cred)
          .then((res) => {
            if (res.data.logged) {
              navigate(`/home/${"sdds"}`);
            } else {
              setError({ name: "password", message: "Incorrect Password" });
            }
          })
          .catch((error) => console.log(error));
      } else {
        setError({ name: "password", message: "Please insert Password" });
      }
    } else {
      setError({
        name: "admission",
        message: "Please insert admission number",
      });
    }
  };

  const [error, setError] = useState({ name: "", message: "" });

  useEffect(() => {
    if (error.name) {
      if (errorTimer.current) clearTimeout(errorTimer.current);
      errorTimer.current = setTimeout(clearError, 3000);
    }
    return () => {
      if (errorTimer.current) clearTimeout(errorTimer.current);
    };
  }, [error]);

  const outputError = (name) =>
    name === error.name && <div className="error">{error.message}</div>;
    
  return (
    <div className="Login">
      <Intro />
      <div className="card grid">
        <div className="institutionDetails">
          <span>
            <h1>Rongo University</h1>
          </span>
          <span>geliana</span>
        </div>
        <div className="formInput">
          <form onSubmit={handleSubmit}>
            <span>
              <h1>Log in</h1>
            </span>
            <div className="inputContainer">
              <label>Admission Number:</label>
              <input 
                type="text" 
                className="input text" 
                onInput={() => error.name === "admission" && clearError()}
              />
              {outputError("admission")}
            </div>
            <div className="inputContainer">
              <label>Password:</label>
              <input 
                type="password" 
                className="input text" 
                onInput={() => error.name === "password" && clearError()}
              />
              {outputError("password")}
            </div>
            <div className="submitContainer">
              <input type="submit" value="Log in" className="button" />
            </div>
          </form>
        </div>
      </div>
    </div>
  );
};

export default Login;

逻辑说明

  • 错误提示默认展示3秒后自动消失,若展示期间触发新的错误,会自动重置倒计时,不会出现多个提示时序冲突问题
  • 用户在报错的对应输入框输入内容时,错误提示会立即消失,不干扰正常输入流程
  • 组件卸载时会自动清理未执行的定时器,不存在内存泄漏风险

内容的提问来源于stack exchange,提问作者stephen telian

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 21:27:20