我试图呈现以下信息到一个组件:
const navigation = [
{
name: "Services",
description: "Our services",
href: "#",
subMenu: [
{ name: "Management" },
{ name: "Development" },
{ name: "Specialists" },
],
},
{
name: "Experts",
description: "our experts",
href: "#",
subMenu: [
{ name: "Engineers" },
{ name: "Project managers" },
{ name: "Developers" },
{ name: "Cloud solutions" },
],
},
所以我尝试了一些不同的方法,但是都不起作用
第一种方法:
{navigation.map((item) => (
<>
<div className=" border-b-2 justify-between pb-4 flex ">
<h3 className="underline-offset-2 ">
{item.description}
</h3>
<div className="border border-solid border-b-2"></div>
<ChevronDownIcon
onClick={() => setShowSubMenu(!ShowSubMenu)}
className="h-5 w-5 "
/>
</div>
<div>{item.subMenu}</div>
</>
))}
给出错误:"对象作为React子对象无效",但我找到的所有指南都说这应该通过使用。map()来解决,但它仍然给出此错误。所以我尝试在组件中再次使用.map():
{navigation.map((menu) => (
<div key={menu.name}>{menu.subMenu}</div>
))}
但是现在它给出了这个错误:"error: objects是无效的"
谢谢你的帮助。
您应该通过subMenu进行映射,因为它本身就是一个数组。类似以下语句:
navigation.map((menu) => (
menu.subMenu.map(sm => {
// do as you need here
})
)