[英]the for Loop inside React JSX
i'm trying to create a table who change dynamically ,the number of its columns changes according to the number of days of the month(28,29,30,31)我正在尝试创建一个动态变化的表,其列数根据一个月的天数(28,29,30,31)而变化
i created the table manually ( but the number of columns is fixed to 31 ) :我手动创建了表(但列数固定为 31):
https://i.stack.imgur.com/pAvPu.png https://i.stack.imgur.com/pAvPu.png
here is the component in which i tried to select the number of columns manualy according to the number of days of the current month (28,29,30,31) ,it shows nothing in the browser :这是我尝试根据当月的天数 (28,29,30,31) 手动选择列数的组件,它在浏览器中没有显示:
//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;
How i can i use a for loop inside this code ?我如何在这段代码中使用 for 循环?
You need to return the td's
from the function you're writing in JSX and call the function as well like this:您需要从您在 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>
);
a more efficient way to render it is to extract the function outside the JSX更有效的渲染方式是在 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>
);
If you want to remove the renderTD
function you can create a new array of length a
but I guess it's not a very efficient method to do this.如果你想删除
renderTD
函数,你可以创建一个长度a
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>
);
The code block inside your jsx does not result in any value. jsx 中的代码块不会产生任何值。
try replacing尝试更换
{() => {
for(let i=1;i<=a;i++){
<td>{i}</td>
}
}}
by something like:通过类似的东西:
Array(a).keys().map((i) => <td>{i-1}</td>)
There may be smarter ways than Array(a).keys()
to generate the value range you need.可能有比
Array(a).keys()
更聪明的方法来生成您需要的值范围。
Better you should use map() Make sure you have your i is an array最好你应该使用 map() 确保你有你的 i 是一个数组
i.map(elem -=> {
return <td>elem</td>
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.