【问题标题】:Submit a form using Enter key with "@material-ui/core/Button" in react.js在 react.js 中使用带有“@material-ui/core/Button”的 Enter 键提交表单
【发布时间】:2020-03-01 03:38:08
【问题描述】:

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

<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>

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

handleSubmit = () => {
  const { dispatch } = this.props;
  const { email, password } = this.state;
  dispatch(loginUser(email, password));
};

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

【问题讨论】:

    标签: javascript reactjs forms material-ui


    【解决方案1】:

    改为使用"submit" 类型的按钮来尝试以下操作。这应该可以使用回车键启用表单提交:

    <Button type="submit" fullWidth variant="contained" color="primary" className={classes.submit}>
      Sign In
    </Button>
    

    对于"submit" 类型,您不需要onClick,因为默认情况下单击提交按钮会触发表单submit 事件。

    【讨论】:

    • 现在可以了。我不得不在 handleSubmit 中使用 event.preventDefault() 来停止重新加载页面。感谢您的帮助:)
    【解决方案2】:

    按钮必须使用type="submit" 例如:

        <Button 
            type="submit" 
            fullWidth 
            variant="contained"
            color="primary"
            className={classes.submit}
        >
            Sign In
        </Button>
    

    【讨论】:

      【解决方案3】:

      Button 中添加type=submit 对我不起作用。 你可以试试这个解决方案here。它使用在 React 中工作的 UseEffect 钩子。

      【讨论】:

      • 很有可能,您的
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-27
      • 1970-01-01
      • 1970-01-01
      • 2014-03-11
      相关资源
      最近更新 更多