在 React 中触发按钮的 onClick 按键
Trigger a button's onClick on key press in React
基本上我有一个没有表单的登录页面,我想在用户按下回车键时触发登录按钮的 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>
但据我所知,没有办法做到这一点...但愿我是错的!如果有人有什么想法,请分享。
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);
}
onKeyPress={event => {if (event.key === "Enter") {function_name}}}
基本上我有一个没有表单的登录页面,我想在用户按下回车键时触发登录按钮的 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>
但据我所知,没有办法做到这一点...但愿我是错的!如果有人有什么想法,请分享。
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);
}
onKeyPress={event => {if (event.key === "Enter") {function_name}}}