这是我的代码:
......
render() {
var menuItems = [
{name: 'Item 1', subMenus: [{name: 'Sub Menu 1-2'}, {name: 'Sub Menu 1-2'}, {name: 'Sub Menu 1-3'}]},
{name: 'Item 2'},
{name: 'Item 3'},
{name: 'Item 4', subMenus: [{name: 'Sub Menu 4-2'}, {name: 'Sub Menu 4-2'}, {name: 'Sub Menu 4-3'}]},
{name: 'Item 5'}
]
var menu = function () {
return (
menuItems.forEach(function (menuItem, i) {
if (menuItem.subMenus != undefined) {
<ul key={i}>menuItem.name
menuItem.subMenus.forEach(function (subMenu, i) {
<li key={i}>subMenu.name</li>
}
</ul>
} else {
// do nothing
}
})
)
}
return({menu})
......
显然它不起作用。
通过嵌套菜单循环的正确程序是什么? 提前谢谢。
答案 0 :(得分:1)
return (
<div>
{/* GJK forgot to encapsulate mapping in curly braces */}
{menuItems.map(function(menuItem, i) {
if (menuItem.subMenus != undefined) {
return (
<ul key={i}>{menuItem.name}
{menuItem.subMenus.map(function(subMenu, i) {
return <li key={i}>{subMenu.name}</li>;
})}
</ul>
)
} else {
return (
<ul key={i}>{menuItem.name}</ul>
)
}
})};
</div>)
答案 1 :(得分:0)
这里有几个问题:
forEach()
来电而非map()
来电。你正在创建ul
组件,但是你没有对它们做任何事情,它们只是被扔掉了。render
方法返回任何组件,而是返回一个包含将生成组件的函数的对象。render
返回组件列表。我将所有内容都包装在div
中以解决该问题。这就是你需要的:
return (
<div>
{menuItems.map(function(menuItem, i) {
if (menuItem.subMenus != undefined) {
return (
<ul key={i}>
{/* Not sure this is what you meant, but I added it anyway */}
{menuItem.name}
{menuItem.subMenus.map(function(subMenu, i) {
return <li key={i}>{subMenu.name}</li>;
})}
</ul>
);
} else {
return undefined;
}
})}
</div>
);