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

如何在React JSX中使用for循环渲染按当月天数动态调整的表格列

问题原因

你的代码存在两个核心问题:

  • 你在JSX的花括号中定义了一个匿名函数,但没有执行它,React不会主动调用这个函数生成内容
  • 即使你执行了这个函数,普通for循环没有返回值,也没有把生成的<td>元素收集起来,React还是拿不到要渲染的内容

方案1:用for循环提前收集元素

你可以在return语句之前先把所有<td>元素存到数组里,再把数组放到JSX对应的位置即可,注意要给每个列表元素加唯一的key属性,避免React抛出渲染警告:

const Test = () => {
    // 获取当月总天数
    function daysInCurrentMonth() {
        const now = new Date();
        return new Date(now.getFullYear(), now.getMonth()+1, 0).getDate();
    }

    const dayCount = daysInCurrentMonth();
    // 提前收集td元素
    const dayColumns = [];
    for(let i=1; i<=dayCount; i++){
        dayColumns.push(<td key={i}>{i}</td>)
    }

    return (
        <div>
            <table>
                <tbody>
                    <tr>
                        {dayColumns}
                    </tr>
                </tbody>
            </table>
        </div>
    );
}

export default Test;

方案2:用Array.from简化代码(不需要手写for循环)

如果不想单独声明数组遍历,也可以直接用Array.from生成对应长度的元素数组,写法更简洁:

const Test = () => {
    // 获取当月总天数
    function daysInCurrentMonth() {
        const now = new Date();
        return new Date(now.getFullYear(), now.getMonth()+1, 0).getDate();
    }

    const dayCount = daysInCurrentMonth();

    return (
        <div>
            <table>
                <tbody>
                    <tr>
                        {Array.from({length: dayCount}, (_, index) => (
                            <td key={index + 1}>{index + 1}</td>
                        ))}
                    </tr>
                </tbody>
            </table>
        </div>
    );
}

export default Test;

两种方案都可以实现根据当月天数动态生成对应列数的效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 05:45:03