onKeyDown event not working on divs in React

前端 未结 7 1155
北恋
北恋 2020-12-02 11:11

I want to use a keyDown event on a div in React. I do:

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


        
7条回答
  •  天涯浪人
    2020-12-02 11:33

    You're thinking too much in pure Javascript. Get rid of your listeners on those React lifecycle methods and use event.key instead of event.keyCode (because this is not a JS event object, it is a React SyntheticEvent). Your entire component could be as simple as this (assuming you haven't bound your methods in a constructor).

    onKeyPressed(e) {
      console.log(e.key);
    }
    
    render() {
      let player = this.props.boards.dungeons[this.props.boards.currentBoard].player;
      return (
        
    ) }

提交回复
热议问题