Trigger a button's onClick on key press in React

对着背影说爱祢 提交于 2020-04-07 01:23:09

问题


So basically I have a login page without a form and I want to trigger the login button's onClick when the user presses enter.

I tried adding an event listener to the page like so:

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

The problem is that that listener is instantiated when the component mounts which means that the props username and password are in their initial state (i.e. empty).

Adding the event listener to componentWillReceiveProps doesn't work for similar reasons.

Basically with this solution I'd need to not send username and password from the function in the event listener and instead fetch username and password from the state in mapDispatchToProps where the function in the event listener is defined, but that's a very ugly solition.

What I was looking for in the beginning was to add a listener to the button similar to onClick and basically as such:

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

But as far as I know there is no way of doing that... hopefully I'm wrong though! If anyone has some ideas, please share.


回答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);
}



回答2:


onKeyPress={event => {if (event.key === "Enter") {function_name}}}



来源:https://stackoverflow.com/questions/42815909/trigger-a-buttons-onclick-on-key-press-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!