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

React中是否有符合指定用法的useSleep hook实现无人操作自动休眠功能

自定义useSleep Hook实现方案

首先修正你示例代码中的一处错误:你在调用useSleep时传入的是setSleepMode(),这会在组件初始化时直接执行休眠函数,正确写法是传入函数引用setSleepMode。

以下是完全符合你预期用法的Hook实现:

import { useRef, useEffect, useMemo } from 'react';

const useSleep = (sleepCallback, config) => {
  const timerRef = useRef(null);
  const { timer: timeoutDuration } = config;

  // 重置倒计时计时器
  const resetTimer = () => {
    if (timerRef.current) {
      clearTimeout(timerRef.current);
    }
    timerRef.current = setTimeout(sleepCallback, timeoutDuration);
  };

  // 组件挂载启动计时,卸载时清除计时器避免内存泄漏
  useEffect(() => {
    resetTimer();
    return () => {
      if (timerRef.current) {
        clearTimeout(timerRef.current);
      }
    };
  }, [sleepCallback, timeoutDuration]);

  // 返回绑定到容器的事件集合,直接展开即可使用
  return useMemo(() => ({
    onMouseMove: resetTimer,
    onMouseDown: resetTimer,
    onKeyDown: resetTimer,
    onTouchStart: resetTimer,
    onScroll: resetTimer,
    onMouseEnter: resetTimer
  }), []);
};

修正后的调用示例:

const MyApp = (): JSX.Element => {
  const sleepConfig = {
    timer: 100000 // 100秒无交互触发休眠
  }
  const setSleepMode = () => {
    console.log("setting to sleep mode")
    // 此处可补充你的自定义休眠逻辑,比如切换屏保、重置页面状态等
  }
  // 注意此处传入的是setSleepMode函数引用,不是执行结果
  const sleepEvent = useSleep(setSleepMode, sleepConfig)

  return <div {...sleepEvent}>BODY</div>
};

功能说明

  • 覆盖监听鼠标、键盘、触摸、滚动等全场景交互事件,任意操作触发后都会自动重置休眠倒计时
  • 计时器通过useRef存储,不受组件重渲染影响,计时逻辑稳定
  • 如果需要额外监听其他交互事件,直接在返回的事件对象中补充对应绑定即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 23:06:07