反应键盘事件不触发

Aus*_*cus 2 javascript frontend web reactjs

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

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'));
Run Code Online (Sandbox Code Playgroud)

即使没有Web Audio的东西,我也无法显示日志语句。我已经阅读了React Event System文档,没有发现任何有用的东西,并且我使用鼠标和change事件编写了其他React组件也没有问题-这似乎是键盘事件所特有的。任何帮助将不胜感激!

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

Ale*_*lan 6

A <div>是容器元素,而不是input元素。键盘事件仅由产生<inputs><textarea>并与任何contentEditable属性。

你可以试试

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

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


Phy*_*Rex 6

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

直接的

正如在类似的 SO 问题“onKeyDown 事件不适用于 React 中的 div”(以及ncubica的评论中)中提到的,包括tabIndex="0",例如:

<div 
  id="keyboard"
  tabIndex="0" 
  onKeyDown={this.playNote}
  onKeyUp={this.stopNote}>
</div>
Run Code Online (Sandbox Code Playgroud)

变通方法

只需eventListener()在您的componentWillMount()生命周期中添加一个 vanillaJS ,它就会在您的页面呈现时加载事件侦听器(此处的详细信息:将生命周期方法添加到类

document.addEventListener("keydown", this.playNote);
document.addEventListener("keyup", this.stopNote);
Run Code Online (Sandbox Code Playgroud)