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

如何使用React.js实现带起止时间日期记录的functional component计数器

React 函数式计数器组件实现

我们基于useState和useRef两个React Hook实现需求,修正了原参考代码中父级div绑定点击事件导致误触发的问题,完整代码如下:

import { useState, useRef } from 'react';

const Counter = () => {
  // 存储当前计数值
  const [count, setCount] = useState(0);
  // 存储启动操作的时间日期
  const [startTime, setStartTime] = useState(null);
  // 存储停止操作的时间日期
  const [stopTime, setStopTime] = useState(null);
  // 用useRef存储定时器ID,不会随组件重渲染丢失
  const timerIdRef = useRef(null);

  const handleStart = () => {
    // 避免重复启动多个定时器
    if (timerIdRef.current) return;
    // 保存当前启动时间,可根据需要调整时间格式
    setStartTime(new Date().toLocaleString());
    // 启动定时器,每秒计数+1
    timerIdRef.current = setInterval(() => {
      setCount(prevCount => prevCount + 1);
    }, 1000);
  };

  const handleStop = () => {
    if (!timerIdRef.current) return;
    // 清除定时器
    clearInterval(timerIdRef.current);
    timerIdRef.current = null;
    // 保存当前停止时间
    setStopTime(new Date().toLocaleString());
  };

  return (
    <div>
      <h2>timer</h2>
      {/* 可选展示内容,不需要可以删除 */}
      <p>当前计数:{count}</p>
      {startTime && <p>上次启动时间:{startTime}</p>}
      {stopTime && <p>上次停止时间:{stopTime}</p>}

      <div>
        <button onClick={handleStart}>Start</button>
        <br />
        <button onClick={handleStop}>Stop</button>
      </div>
    </div>
  );
};

export default Counter;

实现说明

  • 计数器默认1秒累加1次,你可以修改setInterval的第二个参数调整计数间隔
  • 启动和停止的时间日期默认存在startTime和stopTime两个state变量中,你可以直接在组件内部其他逻辑中调用
  • 新增了重复启动拦截逻辑,不会出现多个定时器同时运行导致计数速度异常的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 01:36:03