React-Redux:绑定按键动作以启动减速器序列的规范方法是什么?

swy*_*wyx 4 reactjs redux react-redux

这是一个关于react-redux的新手问题我在找到之前花了几个小时打猎,所以我发布了问题,然后回答后代,也许还有代码审查.

我正在使用react-redux创建一个游戏,我想使用WASD键在小地图周围移动一个角色.(这只是一个更大努力的实践范例).地图只是由一堆彩色的<div>s组成.

据我了解,我需要以某种方式 keypress 事件绑定到React DOM中的某些内容,以便触发mapDispatchToProps,然后启动reducers的重新评估.问题是,这是一个按键,没有什么可以约束的.我正在使用jquery来绑定按键并调用该函数.

相关查询:

jus*_*ris 5

您基本上可以在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)
Run Code Online (Sandbox Code Playgroud)

handleKeyPress 调用动作创建者,将动作降低到减速器.