目前只获取itemList中每个对象的第一个值:
姓名 | 描述 | 详情 |
---|---|---|
1 | 2 | 3 |
itemList = [
{
id: 1,
name: "item1",
description: "description1",
details: "detail1"
},
{
id: 2,
name: "item2",
description: "description1",
details: "detail2"
},
{
id: 3,
name: "item3",
description: "description1",
details: "detail3"
}
];
function Items() {
const handleRender = () => {
return itemList.map((item) => {
for (let entry in item) {
return (
<div className="grid-item" key={item.id}>
{item[entry]}
</div>
);
}
});
};
return (
<div className="grid-container">
<div className="grid-item">name</div>
<div className="grid-item">description</div>
<div className="grid-item">details</div>
{handleRender()}
</div>
);
}
我尝试以不同的方式循环,但我要么得到一个包含所有 itemList 条目的 div 作为一个网格项,要么只得到每个对象的第一个值。
我想要三列:
姓名 | 描述 | 详情 |
---|---|---|
item1 | 说明1 | 细节1 |
项目2 | 说明2 | 细节1 |
item3 | 说明3 | 细节1 |
我怎样才能做到这一点?
甚至可以使用 CSS 网格吗?
你可以使用 HTML 表格来产生这种类型的输出 例如
<table>
<thead>
<tr>
<th>name</th>
<th>description</th>
<th>details</th>
</tr>
</thead>
<tbody>
{
itemList.map((item) => {
return <tr>
<td>{item.name}</td>
<td>{item.description}</td>
<td>{item.details}</td>
</tr>
})
}
</tbody>
</table>
我们可以重构handleRender 像这样
const handleRender = () => {
return itemList.map((item) => {
return Object.keys(item).map((key, index) => {
return (
<div className="grid-item" key={item.id}>
{item[key]}
</div>
);
});
});
};
您可以使用单个
map
功能来显示您的项目。并使用属性来显示“单元格”。
export default function Items() {
return (
<div className="grid-container">
<div className="grid-item">name</div>
<div className="grid-item">description</div>
<div className="grid-item">details</div>
{itemList.map((item) => {
return (
<>
<div className="grid-item">{item.name}</div>
<div className="grid-item">{item.description}</div>
<div className="grid-item">{item.details}</div>
</>
);
})}
</div>
);
}
你的 css 可能看起来像这样。
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
}