在React中递归渲染嵌套数据

我将如何呈现一个带有嵌套<ul>项目的菜单,而该嵌套项目的子对象数量不明,如下面的示例所示,该对象的反应如何?

[

{

title: "Top level 1",

slug: "top-level-1",

children: [

{

title: "Sub level 1",

slug: "sub-level-1",

children: [

{

title: "Sub Sub Level 1"

slug: "sub-sub-level-1"

}

]

}

{

title: "Sub level 2",

slug: "sub-level-2"

}

]

},

{

title: "Top level 2",

slug: "top-level 2"

}

]

回答:

Codesandbox示例

您只需要递归调用Menu组件,其子组件即可显示并作为数据道具传递。

let data = [

{

title: "Top level 1",

slug: "top-level-1",

children: [

{

title: "Sub level 1",

slug: "sub-level-1",

children: [

{

title: "Sub Sub Level 1",

slug: "sub-sub-level-1",

children: [

{

title: "Sub Sub Level 2",

slug: "sub-sub-level-2"

}

]

}

]

},

{

title: "Sub level 2",

slug: "sub-level-2"

}

]

},

{

title: "Top level 2",

slug: "top-level 2"

}

];

const Menu = ({data}) => {

return (

<ul>

{data.map(m => {

return (<li>

{m.title}

{m.children && <Menu data={m.children} />}

</li>);

})}

</ul>

);

}

const App = () => (

<div style={styles}>

<Hello name="CodeSandbox" />

<h2>Start editing to see some magic happen {'\u2728'}</h2>

<Menu data={data} />

</div>

);

以上是 在React中递归渲染嵌套数据 的全部内容, 来源链接: utcz.com/qa/427561.html

回到顶部