React not responding to key down event

后端 未结 4 895
死守一世寂寞
死守一世寂寞 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:48

    The problem is that ChildComponent is not a component but a component factory. It will be replaced with the result of rendering the element created with that factory.

    Insert the ChildComponent in a div and attach any event listener to the div, not ChildComponent. Replace

    with if you need inline display.

    let {Component} = React;
    
    class ChildComponent extends Component {
      render() {
        return ( press down a key );
      }
    }
    
    class App extends Component {
      handleKeyDown(event) {
        console.log('handling a key press');
      }
    
      render() {
        return ( 
    ); } } React.render(, document.getElementById('app'));

    See it in action on codepen

提交回复
热议问题