ref 操作 React 定时器

秒表

image.png

需要将 interval ID 保存在 ref 中,以便在需要时能够清除计时器。

import {
    
     useRef, useState } from "react";

const SecondWatch = () => {
    
    
  const [startTime, setStartTime] = useState<any>(null);
  const [now, setNow] = useState<any>(null);
  const intervalRef = useRef<any>(null);

  function handleStart() {
    
    
    // Date.now() 用于获取当前时间的时间戳。它返回的是一个表示当前时间的整数值,以毫秒为单位。
    setStartTime(Date.now());
    setNow(Date.now());

    // 清除上一个定时器
    clearInterval(intervalRef.current);
    // 定时器
    intervalRef.current = setInterval(() => {
    
    
      setNow(Date.now());
    }, 10);
  }

  function handleStop() {
    
    
    // 关闭定时器
    clearInterval(intervalRef.current);
  }

  let secondsPassed = 0;
  // 毫秒数除以 1000,以将其转换为秒。
  if (startTime != null && now != null) {
    
    
    secondsPassed = (now - startTime) / 1000;
  }

  return (
    <>
      <h1>秒表计时: {
    
    secondsPassed.toFixed(3)}</h1>
      <button onClick={
    
    handleStart}>开始</button>
      <button onClick={
    
    handleStop}>暂停</button>
    </>
  );
};

export default SecondWatch;


使用了 useRef 创建了一个名为 intervalRef 的引用对象,初始值为 null。当点击 “Start” 按钮时,我清除了之前可能存在的计时器(如果有),并创建了一个新的计时器。计时器的 ID 被保存在 intervalRef.current 中。

当点击 “Stop” 按钮时,我清除了当前的计时器,并将 intervalRef.current 重置为 null

这样,我们通过 intervalRef.current 来保存和更新计时器的 ID,在需要时可以清除计时器,同时避免了将计时器显示在界面上。

猜你喜欢

转载自blog.csdn.net/wbskb/article/details/132655321
今日推荐