我在React Js中有点陌生,我想从多维数组渲染菜单,我尝试了下面的代码,该代码在level0菜单上工作正常,但在子菜单上工作不正常。
class MainMenu extends React.Component {
constructor (props) {
super(props)
this.state = {
mainmenu: [
{
name: 'Men',
url: 'men.html',
childrens: [
{
childrenName: 'Men Cloths',
childrenUrl: 'men-cloths.html'
}
]
},
{
name: 'Women',
url: 'women.html',
childrens: [
{
childrenName: 'Women Cloths',
childrenUrl: 'women-cloths.html'
}
]
}
]
};
}
render () {
return (
<div>
<ul>
{this.state.mainmenu.map((item, index) =>
<li key={index}>
<a href={item.url}>{item.name}</a>
<ul>
<li>
<a href={item.childrenUrl}>{item.childrenName}</a>
</li>
</ul>
</li>
)}
</ul>
</div>
)
}
}
ReactDOM.render(
<MainMenu />,
document.getElementById('root')
)
下面的代码结果屏幕截图:
有人可以帮助修复它。 谢谢
答案 0 :(得分:0)
您需要在主映射中使用另一个映射来呈现子项。
render () {
return (
<div>
<ul>
{this.state.mainmenu.map((item, index) =>
<li key={index}>
<a href={item.url}>{item.name}</a>
<ul>
{
item.childrens.map(
(childItem, index2) =>
<li key={`${index}-${index2}`}>
<a href={childItem.childrenUrl}>
{childItem.childrenName}
</a>
</li>
)
}
</ul>
</li>
)}
</ul>
</div>
)
}