React not responding to key down event

后端 未结 4 901
死守一世寂寞
死守一世寂寞 2021-02-02 17:16

I\'m trying to implement some very basic key press detection and I can\'t get it to work at all. I have a bare component that should be picking up on the onKeyDown

4条回答
  •  灰色年华
    2021-02-02 17:59

    The DOM wants the element to be focused in order to receive the keyboard event. If you don't want to hack the element with tabIndex or contentEditable to get it to focus, you could use native DOM event listeners on window, and define a different handler in each component that handles keyboard events.

    Just be sure to remove the event listener when that component unmounts so all components aren't handling all the time:

      componentWillMount: function() {
        window.addEventListener('keydown', this.handleKeyDown);
      },
    
      componentWillUnmount: function() {
        window.removeEventListener('keydown', this.handleKeyDown);
      },
    

    Also, there appears to be an npm that provides similar functionality if that's easier: https://www.npmjs.com/package/react-keydown

提交回复
热议问题