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

如何将生成的格式化时间字符串渲染到React.js的JSX div节点中

可行实现方案

你可以直接在组件的render方法内先计算生成格式化的时间节点数组,再直接插入到JSX结构中即可,完整实现代码如下:

class SchedulePage extends React.Component {
    render(){
        // 生成时间列表逻辑
        const N = 13;
        const nums = Array.apply(1, { length: N }).map(Number.call, Number)
        // 把时间处理为JSX节点数组
        const timeList = nums.map(el => {
            // 写法1:用padStart简化前导0补充逻辑,等价于你原有if判断效果
            const time = `${el.toString().padStart(2, '0')}:00`
            // 可根据需要替换为div/li等其他标签,记得添加唯一key属性
            return <div key={el} className="time-item">{time}</div>
        })

        // 写法2:完全沿用你原有逻辑的写法,效果和上面一致,二选一即可
        // const timeList = []
        // for (let el of nums) {
        //   let time;
        //   if (el <= 9) {
        //     time = `0`+el+`:00`;
        //   } else if (el >= 9) {
        //     time = el+`:00`
        //   }
        //   timeList.push(<div key={el} className="time-item">{time}</div>)
        // }
        
        return (
            <div className="schedule-page-container">
                {/* 直接插入生成的时间列表 */}
                {timeList}
            </div>
        );
    }
}

注意事项

  • 原有代码未声明time变量,上述实现补充了变量声明避免全局变量污染
  • 每个渲染的列表项都添加了唯一key属性,符合React列表渲染规范
  • 如需调整时间项的渲染样式,直接修改time-item类的CSS即可

内容的提问来源于stack exchange,提问作者Zulzidan.com

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 22:27:04