反应键盘事件不触发

React keyboard events not firing

我有一个简单的 React 组件,它应该通过 Web Audio API 在 keyDown 上播放音频,并在 keyUp 上停止音频。我 have a JSFiddle 显示了我在本地主机上看到的相同行为。这是内联代码:

var Keyboard = React.createClass({
  componentDidMount: function () {
    var context = new (window.AudioContext || window.webkitAudioContext)();
    var oscillator = context.createOscillator();
    var gain = context.createGain();

    oscillator.type = 'sine';
    oscillator.frequency.value = 3000;
    gain.gain.value = 0.5;

    oscillator.connect(gain);
    gain.connect(context.destination);

    this.setState({
      context: context,
      oscillator: oscillator,
      gain: gain
    });
  },

  render: function() {
    return (
      <div id="keyboard"
           onKeyDown={this.playNote}
           onKeyUp={this.stopNote}>
      </div>
    );
  },

  playNote: function (ev) {
    console.log('play');
    this.state.oscillator.start();
  },

  stopNote: function (ev) {
    console.log('stop');
    this.state.oscillator.stop();
  }
});

React.render(<Keyboard />, document.getElementById('container'));

即使没有网络音频,我也无法显示日志语句。我已经阅读了 React 事件系统文档,但没有看到任何有用的信息,而且我已经使用鼠标和更改事件编写了其他 React 组件,没有任何问题——这似乎是键盘事件所特有的。任何帮助将不胜感激!

编辑:更正了网络音频 API 调用。应该是 start(),而不是 play()。

<div> 是容器元素,而不是 input 元素。键盘事件仅由 <inputs><textarea> 和任何具有 contentEditable 属性的东西生成。

你可以试试

render: function() {
    return (
      <div id="keyboard"
           contentEditable={true}
           onKeyDown={this.playNote}
           onKeyUp={this.stopNote}>
      </div>
    );
}

但这不是一个有保证的解决方案..只是一个起点:)

我刚遇到这个问题,找到了两个解决方案:

直接

As mentioned in a similar SO question (and also in the comments by ), include tabIndex="0", 例如:

<div 
  id="keyboard"
  tabIndex="0" 
  onKeyDown={this.playNote}
  onKeyUp={this.stopNote}>
</div>

解决方法

只需将 vanillaJS eventListener() 添加到您的 componentWillMount() 生命周期中,它就会在您的页面呈现时加载事件侦听器(此处有详细信息:Adding Lifecycle Methods to a Class

document.addEventListener("keydown", this.playNote);
document.addEventListener("keyup", this.stopNote);