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
相关产品推荐
相关产品推荐

