gpt4 book ai didi

javascript - 在 React 中递归渲染嵌套数据

转载 作者:行者123 更新时间:2023-12-01 05:18:11 25 4
gpt4 key购买 nike

我将如何渲染带有嵌套 <ul> 的菜单具有未知数量子级的项目与对象发生 react ,如以下示例所示?

[
{
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 example

您只需递归调用 Menu 组件即可使其子组件显示并作为数据 Prop 传递。

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>
);

关于javascript - 在 React 中递归渲染嵌套数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47526068/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com