Reactjs 在物料ui登录表单中单击“提交”时未传递数据
我已经使用material ui在reactjs中创建了一个登录表单,但当我单击submit按钮时,我的数据没有被传递。现在,我试图从var body控制台记录密码和电子邮件,但我没有定义。我想知道我哪里做错了。甚至useState中的电子邮件和密码也没有被突出显示,所以我认为它们很可能没有被使用Reactjs 在物料ui登录表单中单击“提交”时未传递数据,reactjs,Reactjs,我已经使用material ui在reactjs中创建了一个登录表单,但当我单击submit按钮时,我的数据没有被传递。现在,我试图从var body控制台记录密码和电子邮件,但我没有定义。我想知道我哪里做错了。甚至useState中的电子邮件和密码也没有被突出显示,所以我认为它们很可能没有被使用 const performLogin = async (event, email, password) => { event.preventDefault(); var body =
const performLogin = async (event, email, password) => {
event.preventDefault();
var body = {
password: password,
email: email
};
console.log(body);
};
export default function Demo() {
const classes = useStyles();
const [email, setEmail] = useState(""); //email and password are not highlighted so that means they're not being used anywhere
const [password, setPassword] = useState("");
return (
<Container component="main" maxWidth="xs">
<CssBaseline />
<div className={classes.paper}>
<Avatar className={classes.avatar}>
<LockOutlinedIcon />
</Avatar>
<Typography component="h1" variant="h5">
Sign in
</Typography>
<form
className={classes.form}
noValidate
onSubmit={(event, email, password) =>
performLogin(event, email, password)
}
>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
id="email"
label="Email Address"
name="email"
autoComplete="email"
autoFocus
onChange={email => setEmail(email)}
/>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
autoComplete="current-password"
onChange={password => setPassword(password)}
/>
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
className={classes.submit}
>
Sign In
</Button>
<Grid container>
<Grid item xs>
<Link href="#" variant="body2">
Forgot password?
</Link>
</Grid>
<Grid item>
<Link href="#" variant="body2">
{"Don't have an account? Sign Up"}
</Link>
</Grid>
</Grid>
</form>
</div>
</Container>
const performLogin=async(事件、电子邮件、密码)=>{
event.preventDefault();
变量体={
密码:密码,
电邮:电邮
};
控制台日志(主体);
};
导出默认函数Demo(){
const classes=useStyles();
const[email,setEmail]=useState(“”;//电子邮件和密码没有突出显示,这意味着它们没有在任何地方使用
const[password,setPassword]=useState(“”);
返回(
登录
performLogin(事件、电子邮件、密码)
}
>
设置电子邮件(电子邮件)}
/>
设置密码(密码)}
/>
登录
忘记密码了?
{“没有帐户?注册”}
onChnage将事件作为参数而不是值本身提供
onChange={e => setEmail(e.target.value)}
onChange={e => setPassword(e.target.value)}
您的代码中有一些错误:
onSubmit={(事件、电子邮件、密码)=>
performLogin(事件、电子邮件、密码)
}
这个onSubmit调用在形式上是可以的,但它是多余的:您的这个电子邮件和密码已经存储在一个钩子上,所以您不需要将它传递给performLogin
函数,问题是您的onChange调用没有更新值:
onChange={email=>setEmail(email)}
因此,首先,我们将解决这个onChange函数,它应该如下所示:
onChange={(事件)=>setEmail(event.target.value)}
现在钩子已正确更新,现在您可以在函数中的任何位置调用它们,onSubmit可以如此简单:
onSubmit={performLogin}
然后你可以看到调用钩子的值:
performLogin(事件){
event.preventDefault();
警报(“已提交电子邮件:”+电子邮件);
警报(“已提交通行证:”+密码);
}
这将帮助您: