React中TypeError: e.preventDefault is not a function问题求助
React登录注册表单错误修复
问题描述
开发登录注册小项目时,根据sendprop值切换登录/注册页面逻辑:值为signup时渲染含邮箱、确认密码的注册页面并调用注册API;值为login时执行登录逻辑。但运行时出现两个问题:
- 抛出错误:
TypeError: e.preventDefault is not a function - 控制台警告:
Warning: Expected onSubmit listener to be a function, instead got a value of object type
错误原因
- onSubmit回调执行时机错误:
<form onSubmit={handleSubmit(sendprop)}>的写法会在组件渲染时立即执行handleSubmit函数,而非将其作为提交事件的回调。由于handleSubmit是异步函数,返回的是Promise对象,导致onSubmit接收的不是函数,触发警告。 - 参数传递顺序错误:
handleSubmit定义时第一个参数应为事件对象e,但调用时先传入了sendprop,导致函数内部的e实际是字符串类型的sendprop,自然没有preventDefault方法,触发类型错误。
修复方案
核心修正
- 调整
onSubmit的回调方式,确保传递的是函数而非函数执行结果 - 直接在
handleSubmit中使用组件的sendpropprops,无需额外传参
完整修正代码
const Form = ({ sendprop }) => { const [formValue, setFormValue] = useState({ name: "", email: "", password: "", confirmPassword: "", }); function onFormChange(e) { console.log("target : " + e.target.value); setFormValue({ ...formValue, [e.target.name]: e.target.value }); console.log(formValue); } const handleSubmit = async (e) => { e.preventDefault(); if (sendprop === "signup") { console.log("in handleSubmit"); if (formValue.password === formValue.confirmPassword) { console.log("in if"); const res = await axios.post('http://localhost:8000/signup', { ...formValue }); console.log(res); } } else { const { email, password } = formValue; const body = { email, password }; const res = await axios.post('http://localhost:8000/login', body); console.log(res); } }; return ( <> <form onSubmit={handleSubmit}> <div id="input-div"> {sendprop === "signup" ? <NameInput passState={{ formValue, setFormValue }} /> : ""} <input type={"email"} placeholder="E m a i l A d d r e s s" id="email-input" className="form-input" name="email" onChange={onFormChange} value={formValue.email} /> <div id="border" className="border-div" /> <input type={"password"} placeholder="P a s s w o r d" id="password-input" className="form-input" name="password" onChange={onFormChange} value={formValue.password} /> <div id="border" className="border-div" /> {sendprop === "signup" ? <ConfirmPassword passState={{ formValue, setFormValue }} /> : ""} </div> <div id="submit-btn-div"> <button type={"submit"} id="submit-btn"> S U B M I T </button> </div> {sendprop === "signup" ? <LoginAccount /> : ""} {sendprop !== "signup" ? <CreateAccount /> : ""} </form> </> ); }; export default Form;
关键修复点
- 将
onSubmit={handleSubmit(sendprop)}改为onSubmit={handleSubmit},确保仅在表单提交时执行函数 handleSubmit移除冗余的prop参数,直接使用组件的sendpropprops,保证事件对象e正确传递- 替换冗余空格为空白字符串,避免渲染不必要的文本节点
内容的提问来源于stack exchange,提问作者Lord
相关产品推荐
相关产品推荐

