如何强制 Enter 键触发 "submit" 功能而不需要关注输入

How to force Enter key to trigger "submit" function without need to focus an input

我正在用 react-redux 制作一个应用程序,我想要一个简单的功能,但它开始看起来很难实现。

:)

我希望能够打开我的 web 应用程序(我登陆我的登录屏幕)并按回车键(浏览器已经保存了我的用户名和密码,并且它们已填写在正确的输入字段中)并拥有"enter" 击键触发了我的登录功能,我不需要先点击任何地方来聚焦。

(在非根组件上)

我已经将我的密码输入(最后一个)正确绑定到回车键。

所以当我聚焦密码字段时按回车键有效:

handleSubmit() {
    const { authenticate } = this.props;
    const { tusername, tpassword } = this.state;
    const credentials = {
        username: tusername,
        password: tpassword,
    };
    authenticate(credentials);
}

_handleKeyPress = (e) => {
    if (e.key === 'Enter') {
        this.handleSubmit();
    }
};

render() {
        return (
            <div onKeyPress={this._handleKeyPress} >
                <Card id="signin">
                    <CardImg top width="100%" src={rubisLogo} alt="Rubis" />
                    <InputGroup>
                        <Input
                            placeholder="Nom d'utilisateur"
                            value={this.state.tusername}
                            onChange={this.updateUser}
                        />
                    </InputGroup>
                    <InputGroup>
                        <Input
                            placeholder="Mot de passe"
                            type="password"
                            value={this.state.tpassword}
                            onChange={this.updatePassword}
                            onKeyPress={this._handleKeyPress}
                        />
                    </InputGroup>
                    <div>
                    <Button
                    id="btn"
                    onClick={this.handleSubmit}
                    to="/home">Login
                    </Button>
                    </div>
                    <ModalPassword class="modal" buttonLabel="Mot de passe oublié ?" />
                    <ModalAccount class="modal" buttonLabel="Créer un compte" />
                </Card>
            </div>);
    }

如您所见,我已尝试将其放在 div 上,但没有成功。我也不想要基于此的解决方案。我希望回车键成为此视图的全局后备。用户不能仅仅因为他点击了某个地方就失去了这个功能。

默认使用 tabIndex 将焦点设置到 div,以便触发 javascript 事件

render() {
        return (
            <div onKeyPress={this._handleKeyPress} tabIndex="1" >
                <Card id="signin">
            ..)}

您必须使用表单标签而不是 div 包装您的组件,处理 onSubmit 事件,并且必须将 属性 类型的登录按钮设置为 submit

...
handleSubmit = (e) => {
  e.preventDefault(); // prevent browser behavior
  // Handle submit logic
  ...
};

render() {
  return (
    <form onSubmit={handleSubmit}>
      ...
      <Button
        id="btn"
        type="submit"
        to="/home">Login
      </Button>
    </form>
  );
}