这是一个关于react-redux的新手问题,我花了几个小时四处搜寻才发现,所以我发布了这个问题,然后为后代回答,也可能是代码审查。
我正在使用 React-Redux 创建一个游戏,我想使用 WASD 键在小地图上移动角色。 (这只是更大努力的实践示例)。地图只是由一堆彩色的组成<div>
s.
据我了解,我需要以某种方式将按键事件绑定到 React DOM 中的某些内容为了触发mapDispatchToProps然后开始reducer的重新评估。问题是,这是一个按键,没有什么可以绑定的。我正在使用 jquery 绑定按键并调用该函数。
相关查询:
-
React - 检测更改事件中的“输入”按键 https://stackoverflow.com/questions/36520587/react-detect-enter-key-press-in-change-event这个没有什么帮助,因为它只是绑定到文本区域的 onChange 事件
-
https://facebook.github.io/react/docs/events.html#keyboard-events https://facebook.github.io/react/docs/events.html#keyboard-events没有告诉你如何绑定,事实上我真的不知道如何在元素上使用 onKeyDown !诡异的。
您基本上可以在keypress
事件处理程序
class App extends React.Component {
constructor() {
super();
this.handleKeyPress = this.handleKeyPress.bind(this);
}
handleKeyPress(event) {
// you may also add a filter here to skip keys, that do not have an effect for your app
this.props.keyPressAction(event.keyCode);
}
componentDidMount() {
document.addEventListener('keypress', this.handleKeyPress);
}
componentWillUnmount() {
document.removeEventListener('keypress', this.handleKeyPress);
}
render() {
return <div>Your game content</div>;
}
}
export default connect(mapStateToProps, {keyPressAction})(App)
handleKeyPress
调用动作创建者,这会将动作下推到减速器。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)