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