react不响应按键事件

IT技术 javascript reactjs
2021-05-25 09:44:06

我正在尝试实现一些非常基本的按键检测,但我根本无法让它工作。我有一个应该接收onKeyDown事件的裸组件,但控制台中没有任何内容被注销:

class App extends React.Component {
  constructor(props) {
    super(props);
  }

  handleKeyDown(event) {
    console.log('handling a key press');
  }

  render() {
    return (
      <ChildComponent onKeyDown={this.handleKeyDown} />
    );
  }
}

React.render(<App />, document.getElementById('app'));
4个回答

您需要tabIndex为您的元素(例如包装元素)分配一个-attribute 以接收按键。然后使用 props 将 keyDown 处理程序传递给它:

import React from 'react';
import { render } from 'react-dom';

class ChildComponent extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div tabIndex="0" onKeyDown={this.props.handleKeyDown}>Fooo</div> 
    );
  }
}

class App extends React.Component {
  constructor(props) {
    super(props);
  }

  handleKeyDown(event) {
    console.log('handling a key press');
  }

  render() {
    return (
      <ChildComponent handleKeyDown={() => this.handleKeyDown()} />
    );
  }
}

render(<App />, document.getElementById('app')); 

DOM 希望元素获得焦点以接收键盘事件。如果您不想使用 hack 元素tabIndexcontentEditable使其聚焦,则可以在 上使用本机 DOM 事件侦听器window,并在每个处理键盘事件的组件中定义不同的处理程序。

只要确保在该组件卸载时删除事件侦听器,以便所有组件都不会一直处理:

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

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

此外,如果更容易的话,似乎有一个 npm 可以提供类似的功能:https : //www.npmjs.com/package/react-keydown

问题在于它ChildComponent不是组件而是组件工厂。它将被替换为渲染由该工厂创建的元素的结果。

将 插入ChildComponentdiv 并将任何事件侦听器附加到 div,而不是ChildComponent. 如果需要内嵌显示,请替换<div><span>

let {Component} = React;

class ChildComponent extends Component {
  render() {
    return ( <child-component>press down a key</child-component> );
  }
}

class App extends Component {
  handleKeyDown(event) {
    console.log('handling a key press');
  }

  render() {
    return ( <div onKeyDown={this.handleKeyDown}><ChildComponent  /></div> );
  }
}

React.render(<App />, document.getElementById('app'));

codepen上查看它的实际效果

在我的团队正在开发的应用程序中,我们使用的是react-hotkey不幸的是,React 似乎不支持使用 ES6 语法的 mixin,但是如果你对一些 babel 很酷,你可以尝试一下。

let App = React.createClass({
  mixins: [hotkey.Mixin('handleKeyDown')],

  componentDidMount() {
    hotkey.activate();
  },

  componentWillUnmount() {
    hotkey.disable();
  },

  handleKeyDown(event) {
    console.log('handling a key press');
  },

  render() {
    return (
      <ChildComponent />
    );
  }
});

React.render(<App />, document.getElementById('app'));