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

ReactJS函数组件实现Gmail格式表单验证报错是否需改用类组件?

问题解决方案

无需改写为类组件,报错核心原因是在函数组件中使用了仅类组件支持的this相关语法,按以下步骤修改即可:

  • 第一步:引入useState Hook并声明表单状态和错误状态
import { useState } from 'react';

const Login = () => {
  // 声明表单字段状态和错误状态
  const [fields, setFields] = useState({
    name: '',
    email: '',
    password: ''
  });
  const [errors, setErrors] = useState({});
  // 原有其他注释保留
  // const [name,setName] = useState('Shakthi Saravanan');
  // const {data:blogs, isPending, error} = useFetch('http://localhost:8000/blogs');
  • 第二步:修改handleChange函数,移除this相关调用
function handleChange(field, e) {
    // 用useState返回的setFields方法更新状态,避免直接修改原状态
    setFields(prevFields => ({
      ...prevFields,
      [field]: e.target.value
    }));
  }
  • 第三步:修改handleValidation函数,适配函数组件语法,同时补充Gmail邮箱限定逻辑
function handleValidation() {
    let errors = {};
    let formIsValid = true;

    // 用户名校验
    if (!fields["name"]) {
      formIsValid = false;
      errors["name"] = "Cannot be empty";
    }
    if (typeof fields["name"] !== "undefined") {
      if (!fields["name"].match(/^[a-zA-Z]+$/)) {
        formIsValid = false;
        errors["name"] = "Only letters";
      }
    }

    // Gmail邮箱校验
    if (!fields["email"]) {
      formIsValid = false;
      errors["email"] = "Cannot be empty";
    }
    if (typeof fields["email"] !== "undefined") {
      let lastAtPos = fields["email"].lastIndexOf("@");
      let lastDotPos = fields["email"].lastIndexOf(".");
      // 补充Gmail后缀校验
      const isGmail = fields["email"].endsWith("@gmail.com");

      if (
        !(
          lastAtPos < lastDotPos &&
          lastAtPos > 0 &&
          fields["email"].indexOf("@@") == -1 &&
          lastDotPos > 2 &&
          fields["email"].length - lastDotPos > 2 &&
          isGmail
        )
      ) {
        formIsValid = false;
        errors["email"] = "Please enter a valid Gmail address";
      }
    }

    setErrors(errors);
    return formIsValid;
  }
  • 第四步:修改JSX部分的事件绑定和值绑定,移除this调用,同时补充登录校验触发逻辑(已修正原代码中邮箱输入框错误绑定name字段的问题)
return ( 
    <div className="login-cot bg-danger" id="layoutAuthentication">
      <div id="layoutAuthentication_content">
        <main>
          <div className="container ">
            <div className="row justify-content-center ">
              <div className="col-lg-5 ">
                <div className="card shadow-lg border-0 rounded-lg mt-5 bg-secondary">
                  <center><h1 className="bg-warning" style={{padding:"10px",}}><b><BsBugFill /><BsTools /> <BsColumns />  BFP</b></h1></center>
                  <div className="card-header"><h3 className="text-center my-1"><b>Login</b></h3></div>
                  <div className="card-body">
                    <form onSubmit={(e) => {
                      e.preventDefault();
                      if(handleValidation()) {
                        // 校验通过后跳转至首页
                        window.location.href = '/home';
                      }
                    }}>
                      {/* 邮箱输入框,绑定email字段 */}
                      <div className="form-floating mb-3">
                        <input className="form-control" id="inputEmail" type="email"
                          onChange={(e) => handleChange("email", e)} 
                          placeholder="name@gmail.com"
                          value={fields.email} />
                        <label htmlFor="inputEmail">Gmail address</label>
                        {/* 显示邮箱错误提示 */}
                        {errors.email && <span className="text-danger small">{errors.email}</span>}
                      </div>
                      <div className="form-floating mb-3">
                        <input className="form-control" id="inputPassword" type="password" placeholder="Password"
                          onChange={(e) => handleChange("password", e)}
                          value={fields.password} />
                        <label htmlFor="inputPassword">Password</label>
                      </div>
                     
                      <div className="d-flex align-items-center justify-content-between mt-4 mb-0">
                        <Link className="small text-light" to="/forgotPassword">Forgot Password?</Link>
                        <button type="submit" className="btn btn-success">Login</button>
                      </div>
                    </form>
                  </div>
                  </div>
              </div>
            </div>
          </div>
        </main>
      </div>
    </div>
  );
}

内容的提问来源于stack exchange,提问作者Shanky Boi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 00:54:04