小编典典

onKeyDown事件不适用于React中的div

reactjs

我想在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}

在组件上。但是它没有反应。我记得它可以处理输入元素。

码笔

我该怎么做?


阅读 775

收藏
2020-07-22

共1个答案

小编典典

您应该使用 tabIndex 属性,以便能够在React中的div上监听onKeyDown事件。设置tabIndex =“
0”应该会触发您的处理程序。

2020-07-22