小编典典

在React中触发按钮的onClick按键

reactjs

所以基本上我有一个没有表单的登录页面,我想在用户按下Enter时触发登录按钮的onClick。

我尝试将事件侦听器添加到页面,如下所示:

componentWillMount() {
   const { handleKeyPress, username, password } = this.props;
   document.addEventListener('keydown', (event, username, password) => handleKeyPress(event.key));
}

问题在于,在安装组件时会实例化侦听器,这意味着道具的用户名和密码处于初始状态(即空)。

由于类似的原因,无法将事件侦听器添加到componentWillReceiveProps。

基本上,使用此解决方案,我不需要从事件侦听器中的函数发送用户名和密码,而是从mapDispatchToProps中定义了事件侦听器中的函数的状态中获取用户名和密码,但这是非常丑陋的选择。

一开始我想要的是在按钮上添加一个监听器,类似于onClick,基本上是这样的:

<button
  onEnterKeyPress={() => handleLogin(this.props.username, this.propspassword)}
>
  Log in
</button>

但是据我所知,这是没有办法的……希望我是错的!如果有人有什么想法,请分享。


阅读 1040

收藏
2020-07-22

共1个答案

小编典典

constructor() {
   super();
   this.handleKeyPress = this.handleKeyPress.bind(this);
}

componentWillMount() {
   document.addEventListener('keydown', this.handleKeyPress);
}

handleKeyPress(event) {
   if (event.keyCode !== 13) return;

   const {handleLogin, username, password} = this.props;

   handleLogin(username, password);
}

componentWillUnmount() {
   document.removeEventListener('keydown', this.handleKeyPress);
}
2020-07-22