在 react.js 中使用带有“@material-ui/core/Button”的 Enter 键提交表单

use*_*035 6 javascript forms reactjs material-ui

这是我在渲染方法中的表单,用于用户登录。

<form onSubmit={this.handleSubmit}>
  <Avatar className={classes.avatar}>
    <LockOutlinedIcon />
  </Avatar>
  <Typography component="h1" variant="h5">
    Sign in
  </Typography>

  <TextField variant="outlined" margin="normal" fullWidth id="email"
    label="Email Address" name="email" onChange={this.handleEmailChange}
  />
  <TextField variant="outlined" margin="normal" fullWidth
    name="password" onChange={this.handlePasswordChange}
  />
  {loginError && (
    <Typography component="p" className={classes.errorText}>
      Incorrect email or password.
    </Typography>
  )}

  <Button type="button" fullWidth variant="contained" color="primary"
    className={classes.submit} onClick={this.handleSubmit}
  >
    Sign In
  </Button>
</form>
Run Code Online (Sandbox Code Playgroud)

以下是我的句柄提交方法。

handleSubmit = () => {
  const { dispatch } = this.props;
  const { email, password } = this.state;
  dispatch(loginUser(email, password));
};
Run Code Online (Sandbox Code Playgroud)

如何通过按键提交表单Enter?我正在使用标准的 Material UIButton组件。

Ale*_*sky 19

通过创建类型按钮来尝试以下操作"submit"。这应该使用回车键启用表单提交:

<Button type="submit" fullWidth variant="contained" color="primary" className={classes.submit}>
  Sign In
</Button>
Run Code Online (Sandbox Code Playgroud)

"submit"也不需要type onClick,因为submit默认情况下单击提交按钮会触发表单事件。

  • 现在它正在发挥作用。我必须在handleSubmit 中使用 event.preventDefault() 来停止重新加载页面。感谢您的帮助 :) (4认同)