簡體   English   中英

為什么 onKeyPress 在反應中對我不起作用?

[英]Why onKeyPress doesn't work for me in react?

我想使用 ''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>
  );
};

但這對我不起作用。
注意:它僅在單擊選項卡按鈕后才起作用,但我想在任何按鍵上播放而不使用內部輸入標簽。 完整的代碼是 在這里上codesandbox。

您可以將事件偵聽器附加到要捕獲的 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、shift 等,而 KeyDown 和 KeyUp 則不(請參閱下面有關 esc 的詳細信息);
  • 當您在 Windows 中通過 alt+tab 切換窗口時,只有用於 alt 的 KeyDown 會觸發,因為窗口切換發生在任何其他事件之前(我想,系統阻止了用於 Tab 的 KeyDown,至少在 Chrome 71 中)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM