You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何捕获按键按压时长?React应用功能实现咨询

捕获React中按键按压时长的实现方案

要实现捕获按键按压时长,仅靠onKeyPress事件不够——它只能触发一次按键按下的瞬间。我们需要结合onKeyDown和onKeyUp事件,记录按键按下的时间戳,在按键抬起时计算时长。

以下是改造后的完整代码:

import { KeyboardEvent, useRef } from "react";

const App = () => {
  // 用useRef存储按键按下的时间戳,避免触发组件重渲染
  const keyDownTime = useRef<number | null>(null);

  const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
    // 仅在首次按下时记录时间,避免长按重复触发
    if (!keyDownTime.current) {
      keyDownTime.current = Date.now();
    }
  };

  const handleKeyUp = (e: KeyboardEvent<HTMLInputElement>) => {
    if (!keyDownTime.current) return;

    // 计算按压时长(毫秒)
    const pressDuration = Date.now() - keyDownTime.current;
    keyDownTime.current = null; // 重置时间戳

    // 针对y/n按键的逻辑,带上时长
    if (e.key === "y") {
      alert(`yes,按压时长:${pressDuration}ms`);
    }
    if (e.key === "n") {
      alert(`no,按压时长:${pressDuration}ms`);
    }
  };

  return (
    <div className="App">
      <input
        type="text"
        placeholder="Press the 'y' or 'n' key"
        onKeyDown={handleKeyDown}
        onKeyUp={handleKeyUp}
      />
    </div>
  );
};

export default App;

关键逻辑说明

  • useRef的使用:用来存储按键按下的时间戳,因为它的值更新不会触发组件重渲染,适合跨事件保存临时状态。
  • onKeyDown事件:在按键按下的瞬间记录当前时间,添加判断避免同一按键长按期间重复记录。
  • onKeyUp事件:在按键抬起时计算当前时间与按下时间的差值,得到按压时长,完成后重置时间戳,准备下一次按键监听。

内容的提问来源于stack exchange,提问作者helpmepie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 04:00:46