Javascript React submit表单返回事件。preventDefault不是函数
我在提交简单的注册表格时遇到问题。代码如下:Javascript React submit表单返回事件。preventDefault不是函数,javascript,reactjs,Javascript,Reactjs,我在提交简单的注册表格时遇到问题。代码如下: import React from 'react'; import {register} from 'Util/api' function Registration() { const [email, setEmail] = React.useState("") const [password, setPassword] = React.useState("") const [passwordCheck, setPasswordChe
import React from 'react';
import {register} from 'Util/api'
function Registration() {
const [email, setEmail] = React.useState("")
const [password, setPassword] = React.useState("")
const [passwordCheck, setPasswordCheck] = React.useState("")
const [error, setError] = React.useState("")
const register = event => {
event.stopPropagation()
event.preventDefault()
register(email, password, passwordCheck).then(res => {
console.log(res)
}).catch(error => {
console.log(error)
})
}
return (
<div>
<form onSubmit={register}>
<div>
<label>Email:
<input
type="text"
placeholder="Email"
value={email}
onChange={ev => setEmail(ev.target.value)}
/>
</label>
</div>
<div>
<label>Password:
<input
type="password"
placeholder="Password"
value={password}
onChange={ev => setPassword(ev.target.value)}
/>
</label>
</div>
<div>
<label>Repeat password:
<input
type="password"
placeholder="Repeat password"
value={passwordCheck}
onChange={ev => setPasswordCheck(ev.target.value)}
/>
</label>
</div>
<button type="submit" value="Submit">Register</button>
{error && (
<div>{error}</div>
)}
</form>
</div>
);
}
export default Registration
从“React”导入React;
从“Util/api”导入{register}
函数注册(){
const[email,setEmail]=React.useState(“”)
const[password,setPassword]=React.useState(“”)
const[passwordCheck,setPasswordCheck]=React.useState(“”)
常量[error,setError]=React.useState(“”)
常量寄存器=事件=>{
event.stopPropagation()
event.preventDefault()
注册(电子邮件、密码、密码检查)。然后(res=>{
console.log(res)
}).catch(错误=>{
console.log(错误)
})
}
返回(
电邮:
setEmail(ev.target.value)}
/>
密码:
设置密码(ev.target.value)}
/>
重复密码:
setPasswordCheck(ev.target.value)}
/>
登记
{错误&&(
{错误}
)}
);
}
导出默认注册
当我单击“注册”按钮时,控制台返回错误:
Registration.js:12未捕获类型错误:event.stopPropagation不是函数
如果我删除该行,event.preventDefault
也会发生同样的情况。它看起来与文档中的示例非常相似
我的代码有什么问题?您有名称冲突-有两个标识符名为
register
:
import {register} from 'Util/api'
及
在第二个代码中,您希望引用导入的函数,而不是处理程序,但是由于处理程序在词汇上更接近,register
引用了那里的处理程序-它递归地调用自己,第一个参数是email
,这实际上不是一个事件,因此不能对其调用stopPropagation
和preventDefault
请使用其他名称:
const handleSubmit = event => {
event.stopPropagation()
event.preventDefault()
register(email, password, passwordCheck).then(res => {
console.log(res)
}).catch(error => {
console.log(error)
})
}
您有两个寄存器。请换
const register = event =>
到
及
到
<form onSubmit={handleSubmit}>
const register = event =>
const submitHandler = event =>
<form onSubmit={register}>
<form onSubmit={submitHandler}>