[英]How to render nested map from JSON in React.JS?
我正在嘗試從 JSON 呈現菜單值。 考慮到這是一個多級菜單,我正在嘗試做一個嵌套的 map 來呈現完整的菜單。
const menu = {
data:[
{
title: "Home",
child: [
{
title: "SubLevel1",
child: {
title: "SubSubLevel1"
}
},
{
title: "SubLevel2",
child: [
{title: "SubSubLevel1"},
{title: "SubSubLevel2"}
]
}
]
},
{
title: "About",
},
{
title: "Contact",
}
]}
這是我使用 map function 時的部分:
const MenuNavigation = () => {
return (
{menu.data.map((item) => (
<div>
<ul>{item.title}</ul>
{item.map((sub, id) =>
<li>{sub.child[id].title}</li>
)}
</div>
))}
)
};
我設法為菜單(主頁、關於、聯系人)呈現主級別,但是如何打印子級別和子級別值?
另一個問題:有沒有辦法讓 map 遞歸地成為樹形結構?
試試下面:
menu
應該是這樣的。 您的菜單在數組中未定義的“SubLevel1”子項中存在一個問題。
const menu = {
data: [
{
title: "Home",
child: [
{
title: "SubLevel1",
child: [{
title: "SubSubLevel1",
}],
},
{
title: "SubLevel2",
child: [{ title: "SubSubLevel1" }, { title: "SubSubLevel2" }],
},
],
},
{
title: "About",
},
{
title: "Contact",
},
],
};
像下面這樣遞歸地渲染它。 我添加了一個margin-left 以正確查看級別。
const renderMenu = (menu) => {
return menu.map((item) => (
<div style={{ marginLeft: '25px' }}>
{item.title}
{item.child && renderMenu(item.child)}
</div>
))
}
return <div>{renderMenu(menu.data)}</div>;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.