React not responding to key down event

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

    You'll need to assign a tabIndex-attribute for your element (the wrapping element for example) for it to receive keypresses. Then pass the keyDown handler to it with the props:

    import React from 'react';
    import { render } from 'react-dom';
    
    class ChildComponent extends React.Component {
      constructor(props) {
        super(props);
      }
      render() {
        return (
          
    Fooo
    ); } } class App extends React.Component { constructor(props) { super(props); } handleKeyDown(event) { console.log('handling a key press'); } render() { return ( this.handleKeyDown()} /> ); } } render(, document.getElementById('app'));

提交回复
热议问题