我想每行显示 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>
首先,将数据拆分为每一行的块。试试这个:
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>
)
});
这里的标记是伪代码,没有经过适当的测试,但希望你能理解。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句