React JS认证中'e.preventDefault is not a function'错误修复方法
解决Ant Design Form注册页'e.preventDefault is not a function'错误
错误原因
Ant Design的Form组件onFinish回调接收的参数不是浏览器的submit事件对象,而是表单验证通过后返回的字段值对象。你在handleSubmit里调用event.preventDefault(),相当于给普通对象调用事件方法,必然报错。而且AntD Form默认已经阻止了表单的默认提交行为,完全不需要手动调用这个方法。
修复步骤
- 删掉
handleSubmit里的event.preventDefault()语句 - 移除单独维护email、password的
useState和onChange绑定,直接从onFinish返回的字段值中获取数据,避免状态同步问题 - 调整
handleSubmit的参数为表单值对象,从其中提取所需字段
修改后的完整代码
import React, { useState } from "react"; import { Link } from "react-router-dom"; import { Button, Form, Input } from "antd"; import { UserAuth } from "../context/AuthContext"; import "../sass/main.scss"; const Signup = () => { const [error, setError] = useState(""); const [form] = Form.useForm(); const { createUser } = UserAuth(); const handleSubmit = async (values) => { setError(""); try { const { email, password } = values; await createUser(email, password); console.log("User created successfully"); } catch (error) { setError(error.message); console.log(error.message); } }; return ( <div className="loginFormContainer"> <div className="loginForm"> <header className="loginFormTitle"> <h3 style={{ fontWeight: "550" }}>Create a new account</h3> </header> <p style={{ paddingLeft: "20px" }}> Already have an account? <Link to="/">Sign in.</Link> </p> <Form form={form} onFinish={handleSubmit}> <Form.Item name="email" label="E-mail" rules={[ { type: "email", message: "The input is not valid E-mail!", }, { required: true, message: "Please input your E-mail!", }, ]} > <Input /> </Form.Item> <Form.Item name="password" label="Password" rules={[ { required: true, message: "Please input your password!", }, ]} > <Input.Password /> </Form.Item> <Form.Item> <Button type="primary" htmlType="submit"> Register </Button> </Form.Item> </Form> </div> </div> ); }; export default Signup;
额外说明
AntD Form会自动管理表单字段状态,通过onFinish的values或form.getFieldValue(fieldName)就能拿到最新字段值,无需手动用useState维护状态,既简化代码又避免同步问题。
内容的提问来源于stack exchange,提问作者Vica Udaka
相关产品推荐
相关产品推荐

