为什么onKeyPress在反应上不适合我?

问题描述

我想使用“ onkeypress”事件播放音频

import React,{ useRef } from "react";

export default ({ source }) => {
  const audRef = useRef(null);
  const onPlayHandler = () => {
    audRef.current.play();
    console.log("Key pressed.");
  };
  return (
    <div tabIndex="1" className="drum-pad" onKeyPress={onPlayHandler}>
      <audio ref={audRef} className="clip" controls>
        <source src={source} type="audio/mpeg" />
        <source src={source} type="audio/ogg" />
      </audio>
      W
    </div>
  );
};

但这对我不起作用。
注意:它仅在单击选项卡按钮后才有效,但我想在任何按键上播放,并且不使用内部输入标签。完整的代码是{and {and} here

解决方法

您可以将事件侦听器附加到要捕获的div。但是您的代码看起来不像那个要求。更好的方法是在已安装的dom上添加事件侦听器。您可以执行以下操作:

import React,{ useRef } from "react";

export default ({ source }) => {
  const audRef = useRef(null);

  React.useEffect(() => {
    window.addEventListener("keydown",onPlayHandler);
    return () => {
      window.removeEventListener("keydown",onPlayHandler);
    };
  },[]);
  const onPlayHandler = () => {
    console.log("Key pressed.");
    audRef.current.play();
  };
  return (
    <div tabIndex="1" className="drum-pad">
      <audio ref={audRef} className="clip" controls>
        <source src={source} type="audio/mpeg" />
        <source src={source} type="audio/ogg" />
        <source src={source} type="audio/wav" />
      </audio>
      W
    </div>
  );
};

这里是演示:https://codesandbox.io/s/purple-tdd-fe3e1?file=/src/DrumPad.js:0-672

,

简短答案:尝试使用onKeyUp而不是onKeyPress

长答案:某些键会触发其中一些事件,而不会触发其他事件。例如,

  • KeyPress会忽略删除,箭头,PgUp / PgDn,home / end,ctrl,alt, 移位等,而KeyDown和KeyUp则不(请参阅有关esc的详细信息 下面);
  • 当您在Windows中通过alt + tab切换窗口时,只有alt的KeyDown 触发是因为窗口切换发生在任何其他事件之前(并且 我认为,至少在Chrome中,系统会阻止Tab的KeyDown 71)。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...