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

Antd Statistic.Countdown如何自定义实现数字与单位上下布局?

antd Statistic.Countdown 实现数值+单位上下居中横向排列方案

直接在format属性中插入HTML标签的写法不可行,组件内部会将方括号包裹的内容作为纯文本渲染,不会解析为DOM元素,插入的div标签会被直接转义显示。

最简便的实现方式是使用组件自带的formatter属性自定义渲染逻辑,不需要额外手写倒计时定时器,代码示例如下:

import { Statistic } from 'antd';
const { Countdown } = Statistic;

// 替换为实际的截止时间戳
const deadline = Date.now() + 1000 * 60 * 60 * 24 * 3;

<Countdown
  className="countdown"
  value={deadline}
  formatter={({ days, hours, minutes, seconds }) => {
    // 统一补零,保持两位数显示
    const padZero = (num) => String(num).padStart(2, '0');
    const timeConfig = [
      { val: padZero(days), unit: '天' },
      { val: padZero(hours), unit: '小时' },
      { val: padZero(minutes), unit: '分钟' },
      { val: padZero(seconds), unit: '秒' }
    ];
    return (
      <div style={{ display: 'flex', columnGap: 20 }}>
        {timeConfig.map((item, index) => (
          <div key={index} style={{ textAlign: 'center' }}>
            <div className="time-value">{item.val}</div>
            <div className="time-unit">{item.unit}</div>
          </div>
        ))}
      </div>
    )
  }}
/>

样式调整说明:

  • 外层flex布局天然实现所有时间块横向排列在同一行
  • 每个时间块设置text-align: center即可实现数值在上、单位在下方居中对齐
  • 可以自行调整columnGap控制时间块之间的间距,给.time-value、.time-unit设置字体大小、颜色匹配设计规范

不推荐通过在format中插入HTML标签的方式实现,组件内置XSS过滤逻辑会转义标签内容,即使通过特殊方式绕过也存在安全隐患,自定义formatter是官方支持的标准实现方式,兼容所有antd 4.x、5.x版本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.31 21:15:44