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

使用react-timer-hook时秒表显示单数字,如何为小于10的时间补前导零?

解决方法

react-timer-hook返回的时、分、秒都是原始数字类型,不会自动补零,官方示例的两位数展示是额外做了格式化处理的,你可以任选以下两种方式实现补前导零的需求:


方法1:直接在模板中使用padStart方法

padStart是JavaScript字符串原生方法,可以快速实现补前导零的需求,只需要先把数字转为字符串调用即可:

import React from "react"; 
import { useStopwatch } from "react-timer-hook"; 
export default function MyStopwatch() {    
  const {seconds, minutes, hours, days, isRunning, start, pause, reset } = useStopwatch({ autoStart: true });
  return (
    <div>
      <span>{String(hours).padStart(2,'0')}</span>:<span>{String(minutes).padStart(2,'0')}</span>:<span>{String(seconds).padStart(2,'0')}</span>
    </div>
  ); 
}

方法2:封装通用格式化工具函数

如果多个地方需要用到时间格式化,你可以单独封装一个工具函数复用:

import React from "react"; 
import { useStopwatch } from "react-timer-hook"; 

// 时间补零格式化函数
const formatTime = (timeNum) => {
  return timeNum < 10 ? `0${timeNum}` : timeNum
}

export default function MyStopwatch() {    
  const {seconds, minutes, hours, days, isRunning, start, pause, reset } = useStopwatch({ autoStart: true });
  return (
    <div>
      <span>{formatTime(hours)}</span>:<span>{formatTime(minutes)}</span>:<span>{formatTime(seconds)}</span>
    </div>
  ); 
}

两种方案都可以实现小于10的数值自动补前导零,最终效果和官方示例一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 15:06:03