我在对象数组中有一些数据,我想将其成对放入不同的容器中。
这是虚拟数据数组的结构:
const projects = [
{
title,
text,
...
},
{
title,
text,
...
},
{
title,
text,
...
},
{
title,
text,
...
},
...
]
这是我的组件:
const Home = () => {
return (
<HomePage className="pageContainer">
<div className="projects" style={display: 'flex'}>
{projects.map( (project, index) => {
return <Project key={index} project={project} />
})}
</div>
</HomePage>
)
}
现在效果非常好,但它给了我以下 html:
<div class="projects">
<div class="projectCard">
<!-- content of project[0] -->
</div>
<div class="projectCard">
<!-- content of project[1] -->
</div>
<div class="projectCard">
<!-- content of project[2] -->
</div>
<div class="projectCard">
<!-- content of project[3] -->
</div>
...
</div>
理想情况下,我想要以下内容:
<div class="projects">
<div class="projectRow">
<div class="projectCard">
<!-- content of project[0] -->
</div>
<div class="projectCard">
<!-- content of project[1] -->
</div>
</div>
<div class="projectRow">
<div class="projectCard">
<!-- content of project[2] -->
</div>
<div class="projectCard">
<!-- content of project[3] -->
</div>
</div>
...
</div>
我可能可以采用一种 hacky 方式,如下所示,但必须有更好的方法(这很好用,因为我目前只有四个项目)??
const Home = () => {
return (
<HomePage className="pageContainer">
<div className="projects">
<div className="projectRow">
{projects.map( (project, index) => {
if (index % 2 === 1) {
return <Project key={index} project={project} />
}
})}
</div>
<div className="projectRow">
{projects.map( (project, index) => {
if (index % 2 !== 1) {
return <Project key={index} project={project} />
}
})}
</div>
</div>
</HomePage>
)
}
你可以这样做:
const Home = () => {
const projects: unknown[] = [1, 2, 3, 4, 5, 6, 7, 8];
const groupLength = 2;
if (projects.length % groupLength !== 0) {
// means projects can not be divided into groups
// of "groupLength" without leftovers
return null;
}
const groupsNumber = projects.length / groupLength;
return (
<HomePage className="pageContainer">
<div className="projects">
{[...Array(groupsNumber).keys()].map((_, groupIndex) => (
<div className="projectRow">
{projects
.slice(groupIndex * groupLength, (groupIndex + 1) * groupLength)
.map((project, index) => (
<Project key={groupIndex * groupLength + index} project={project} />
))}
</div>
))}
</div>
</HomePage>
);
};