gpt4 book ai didi

javascript - React 中的 for 循环

转载 作者:行者123 更新时间:2023-12-05 09:30:16 26 4
gpt4 key购买 nike

我正在尝试创建一个动态变化的表。其列数根据月份的天数(28、29、30 或 31)而变化。

我手动建表(但列数固定为31):

/image/pAvPu.png

这是我尝试根据当月的天数 (28,29,30,31) 手动选择列数的组件,它在浏览器中没有任何显示:

const Test = () => {
// Number of days in the current month
function daysInCurrentMonth() {
var now = new Date();
return new Date(now.getFullYear(), now.getMonth()+1, 0).getDate();
}

let a = daysInCurrentMonth();
return (
<div>
<table>
<tbody>
<tr>
{() => {
for(let i=1;i<=a;i++){
<td>{i}</td>
}
}}
</tr>
</tbody>
</table>
</div>
);
}

export default Test;

如何在这段代码中使用 for 循环?

最佳答案

您需要从您在 JSX 中编写的函数返回 td's 并像这样调用该函数:

return (
<div>
<table>
<tbody>
<tr>
{(() => {
let td = [];
for (let i = 1; i <= a; i++) {
td.push(<td key={i}>{i}</td>);
}
return td;
})()}
</tr>
</tbody>
</table>
</div>
);

一种更有效的呈现方式是将函数提取到 JSX 之外:

function daysInCurrentMonth() {
var now = new Date();
return new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate();
}

let a = daysInCurrentMonth();

const renderTD = () => {
let td = [];
for (let i = 1; i <= a; i++) {
td.push(<td key={i}>{i}</td>);
}
return td;
};

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

如果你想删除 renderTD 函数,你可以创建一个长度为 a 的新数组,但我想这不是一个非常有效的方法。

function daysInCurrentMonth() {
var now = new Date();
return new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate();
}
let a = daysInCurrentMonth();

return (
<div>
<table>
<tbody>
<tr>
{[...Array(a).fill(0)].map((_, i) => (
<td key={i}>{i + 1}</td>
))}
</tr>
</tbody>
</table>
</div>
);

关于javascript - React 中的 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69767735/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com