我想每行显示 4 个项目。我有如下标记。根据该标记我需要显示四个 单行中的项目。例如,如果我有 8 个数据,那么将有两行,每行包含 4 项。
如果我在外面循环 <Grid gutters col="cols-4">
那么将会有八个这样的元素,如果我循环
在该元素内将有八个 Cell
元素。此案该如何处理?
这是标记
const data = [
{id: 1, header: 'header', content: 'content', footer: 'footer'},
{id: 2, header: 'header', content: 'content', footer: 'footer'},
{id: 3, header: 'header', content: 'content', footer: 'footer'},
{id: 4, header: 'header', content: 'content', footer: 'footer'},
{id: 5, header: 'header', content: 'content', footer: 'footer'},
{id: 6, head/xer: 'header', content: 'content', footer: 'footer'},
{id: 7, header: 'header', content: 'content', footer: 'footer'},
{id: 8, header: 'header', content: 'content', footer: 'footer'},
]
<Grid gutters col="cols-4">
<Grid.Cell key={datum.id}>
<Card>
<Card.Header>{datum.header}</Card.Header>
<Card.Content>{datum.content}</Card.Content>
<Card.Footer>{datum.footer}</Card.Footer>
</Card>
</Grid.Cell>
<Grid.Cell>
</Grid.Cell>
<Grid.Cell>
</Grid.Cell>
<Grid.Cell>
</Grid.Cell>
</Grid>
<Grid gutters col="cols-4">
<Grid.Cell key={datum.id}>
<Card>
<Card.Header>{datum.header}</Card.Header>
<Card.Content>{datum.content}</Card.Content>
<Card.Footer>{datum.footer}</Card.Footer>
</Card>
</Grid.Cell>
<Grid.Cell>
</Grid.Cell>
<Grid.Cell>
</Grid.Cell>
<Grid.Cell>
</Grid.Cell>
</Grid>
最佳答案
首先,将每行的数据分成多个 block 。试试这个:
let chunks = [];
const columns = 4;
while (data.length > 0) {
chunks.push(data.splice(0, columns));
}
这将从 data
数组中删除长度为 4
的条目,并将它们放入一个多维数组中,如下所示:
[
[
{
"id":1,
"header":"header",
"content":"content",
"footer":"footer"
},
{
"id":2,
"header":"header",
"content":"content",
"footer":"footer"
},
{
"id":3,
"header":"header",
"content":"content",
"footer":"footer"
},
{
"id":4,
"header":"header",
"content":"content",
"footer":"footer"
}
],
[
{
"id":5,
"header":"header",
"content":"content",
"footer":"footer"
},
{
"id":6,
"header":"header",
"content":"content",
"footer":"footer"
},
{
"id":7,
"header":"header",
"content":"content",
"footer":"footer"
},
{
"id":8,
"header":"header",
"content":"content",
"footer":"footer"
}
]
然后您可以循环遍历每个数组以转储标记。
chunks.forEach(row => {
return (
<Grid gutters col="cols-4">
{
row.forEach(col => ({
<Grid.Cell key={col.id}>
<Card>
<Card.Header>{col.header}</Card.Header>
<Card.Content>{col.content}</Card.Content>
<Card.Footer>{col.footer}</Card.Footer>
</Card>
</Grid.Cell>
}));
}
</Grid>
)
});
这里的标记是伪代码,未经正确测试,但希望您能明白。
关于javascript - 显示两行,每行四个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56075494/