onKeyDown 事件不适用于 React 中的 div

新手上路,请多包涵

我想在 React 中的 div 上使用 keyDown 事件。我愿意:

   componentWillMount() {
      document.addEventListener("keydown", this.onKeyPressed.bind(this));
  }

  componentWillUnmount() {
      document.removeEventListener("keydown", this.onKeyPressed.bind(this));
  }

  onKeyPressed(e) {
    console.log(e.keyCode);
  }

  render() {
    let player = this.props.boards.dungeons[this.props.boards.currentBoard].player;
    return (
      <div
        className="player"
        style={{ position: "absolute" }}
        onKeyDown={this.onKeyPressed} // not working
      >
        <div className="light-circle">
          <div className="image-wrapper">
            <img src={IMG_URL+player.img} />
          </div>
        </div>
      </div>
    )
  }

它工作得很好,但我想用 React 风格做更多的事情。我试过了

onKeyDown={this.onKeyPressed}

在组件上。但它没有反应。我记得它适用于输入元素。

密码笔

我该怎么做?

原文由 Michael 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 781
2 个回答

您应该使用 tabIndex 属性才能在 React 中的 div 上侦听 onKeyDown 事件。设置 tabIndex="0" 应该触发你的处理程序。

原文由 burak 发布,翻译遵循 CC BY-SA 4.0 许可协议

你需要这样写

<div
    className="player"
    style={{ position: "absolute" }}
    onKeyDown={this.onKeyPressed}
    tabIndex="0"
  >

如果 onKeyPressed 未绑定到 this ,则尝试使用箭头函数重写它或将其绑定到组件 constructor

原文由 Panther 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进