[英]React Button unable to call method in Function component
I have a React button that is a form and I intend to submit the form when I click on the Button.我有一个 React 按钮,它是一个表单,我打算在单击按钮时提交表单。 Unfortunately, when I click on the button, nothing happens and the page only reloads.
不幸的是,当我点击按钮时,什么也没有发生,页面只会重新加载。 Even when I just try to output to the console nothing happens but when you check the network, you could see an action being performed.
即使我只是尝试将 output 连接到控制台也没有任何反应,但是当您检查网络时,您可能会看到正在执行的操作。
Below is my code which is just a simple login form and a functionality that validates user input.下面是我的代码,它只是一个简单的登录表单和一个验证用户输入的功能。 I need the button to call the function handleSubmit when I click on the button.
当我单击按钮时,我需要该按钮来调用 function handleSubmit 。
export default function Signin() {
const classes = useStyles();
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [usernameError, setUsernameError] = useState('');
const [passwordError, setPasswordError] = useState('');
const validateUsername = () => {
setUsernameError(username.length > 3 ? null : 'Username must be longer than 3 characters')
}
const validatePassword = () => {
setPasswordError(password.length > 7 ? null : 'Password must be longer than 8 characters')
}
const handleSubmit = () => {
//const { history } = this.props;
console.log('testing button')
}
return (
<Grid
className={classes.root}
component="main"
container
>
<CssBaseline />
<Grid
className={classes.image}
item
md={4}
sm={7}
xs={false}
/>
<Grid
component={Paper}
elevation={6}
item
md={8}
sm={5}
square
xs={12}
>
<MuiThemeProvider theme={theme}>
<div className={classes.paper}>
<img
alt="logo"
src={process.env.PUBLIC_URL + '/images/....'}
/>
<Typography
component="h1"
style={{ color: '#E60000' }}
variant="h5"
>
Sign In
</Typography>
<form
className={classes.form}
noValidate
>
<Grid
container
spacing={2}
>
<Grid
item
xs={3}
/>
<Grid
item
xs={6}
>
<TextField
autoComplete="username"
className={`form-control ${usernameError ? 'is-invalid' : ''}`}
fullWidth
id="username"
label="Enter Username"
margin="normal"
name="username"
onBlur={validateUsername}
onChange={e => setUsername(e.target.value)}
required
value={username}
variant="outlined"
/>
<div className={classes.invalidFeedback}>{usernameError}</div>
</Grid>
<Grid
item
xs={3}
/>
<Grid
item
xs={3}
/>
<Grid
item
xs={6}
>
<TextField
autoComplete="current-password"
className={`form-control ${passwordError ? 'is-invalid' : ''}`}
fullWidth
id="password"
label="Password"
margin="normal"
name="password"
onBlur={validatePassword}
onChange={e => setPassword(e.target.value)}
required
type="password"
value={password}
variant="outlined"
/>
<div className={classes.invalidFeedback}>{passwordError}</div>
</Grid>
<Grid
item
xs={3}
/>
<Grid
item
xs={3}
/>
<Grid
item
xs={3}
>
<Button
className={classes.submit}
color="primary"
fullWidth
onClick={handleSubmit}
type="submit"
variant="contained"
>
Sign In
</Button>
<Grid
item
xs={3}
/>
</Grid>
</Grid>
<Grid container>
<Grid
item
xs={3}
/>
<Grid
item
xs={3}
>
<Link
className={classes.link}
to={`${process.env.PUBLIC_URL}/passwordreset`}
variant="body2"
>
<Button
className={classes.submit}
color="primary"
fullWidth
type="submit"
variant="text"
>
Forgot Password
</Button>
</Link>
</Grid>
<Grid item>
<Link
className={classes.link}
to={`${process.env.PUBLIC_URL}/signup`}
variant="body2"
>
<Button
className={classes.submit}
color="primary"
fullWidth
type="submit"
variant="text"
>
New User?
</Button>
</Link>
</Grid>
</Grid>
<Box mt={5}>
<SigninTrouble />
</Box>
</form>
</div>
</MuiThemeProvider>
</Grid>
</Grid>
);
}
In order to use a button with type submit it has to be nested within an html form tag and handle the submission with the onsubmit attribute.为了使用提交类型的按钮,它必须嵌套在 html 表单标签中,并使用 onsubmit 属性处理提交。 Onother option is to attack an onClick event handler to your button and have your submission logic there.
另一种选择是攻击您的按钮的 onClick 事件处理程序,并在那里有您的提交逻辑。
Since you are using Form you need to handle submit method in form instead of your button.由于您使用的是表单,因此您需要在表单而不是按钮中处理提交方法。 Because your button type is submit which triggers the onSubmit event in form.
因为您的按钮类型是提交,它会触发表单中的 onSubmit 事件。
<form onSubmit={handleSubmit}>
<button type="submit"></button>
</form>
If you want to make an async call you need to stop normal event cycle for your form.如果要进行异步调用,则需要停止表单的正常事件循环。
const handleSubmit = (event) => {
// stop redirect
event.preventDefault();
console.log('testing button');
// here you can make your async call
}
Here is very simple example:这是一个非常简单的例子:
import React, {useEffect, useState} from 'react';
function Example(props) {
function clickHandler() {
alert('hi');
}
return (
<div>
<button onClick={clickHandler}>Click here</button>
</div>
);
}
export default Example;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.