React 键盘事件也会触发 SyntheticBaseEvent

时间:2021-03-20 20:23:01

标签: javascript reactjs

我正在尝试在 React 应用程序中监听按键(即 Shift+A)。我已经设置了一个事件侦听器,但是每当我按 Shift+A 时,事件似乎都会触发两次,一次是 KeyboardEvent,第二次是 SyntheticBaseEvent。这导致回调函数被调用两次。

class App extends Component {
    constructor(props) {
        super(props)
     
        this.handleKey = this.handleKey.bind(this);

        this.myDiv = React.createRef();       
        
    }

    componentDidMount() {

        this.myDiv.current.addEventListener('keydown', this.handleKey);
        this.myDiv.current.focus();
    }

    componentWillUnmount() {
        this.myDiv.current.removeEventListener('keydown', this.handleKey);
    }

    
    ...
    

    handleKey(key){
        if (key.key === "A"){
            this.callback()
            console.log(key)
        }
    }

  render() {
      return (
          <div className={"App"} tabIndex={"0"} onKeyDown={this.handleKey} ref={this.myDiv}>
            
          </div>
      )
    }
}

0 个答案:

没有答案
相关问题