英文:
Pass array as prop in React Typescript
问题
我有一个Navbar
组件,其中我正在创建一个NavDropdown
组件,以在Navbar内部使用。我想将数组作为属性传递给NavDropdown
组件,以显示其下拉项。
数组的结构如下:
DropDownItems: [
{
title: "Keywords",
to: "/app/keywords",
},
{
title: "Followers",
to: "/app/followers",
},
{
title: "Following",
to: "/app/following",
},
]
然而,我遇到了以下两个错误:
- 属性'map'不存在于类型'SubItemsProps'上。
- 参数'subItem'隐式具有'any'类型。
Navbar.tsx
type SubItemsProps = {
subItems: DropdownItem[];
};
interface DropdownItem {
subTitle: string;
subLink: string;
}
const NavDropdown = ({
title,
subItems
}: {
title: string;
subItems: SubItemsProps;
}) => {
return (
<div>
<div>{title}</div>
<div>
<ul>
{subItems.map(subItem => (
<Link href={subItem.subLink}>
<li>
<span>{subItem.subTitle}</span>
</li>
</Link>
))}
</ul>
</div>
</div>
);
};
/* Navbar component */
请注意,我只翻译了代码部分,没有添加其他内容。
英文:
I've Navbar
component inside which I'm creating a NavDropdown
component to use inside the Navbar. I want to pass array as prop to the NavDropdown
component to display its dropdown items.
The array will be of structure:
DropDownItems: [
{
title: "Keywords",
to: "/app/keywords",
},
{
title: "Followers",
to: "/app/followers",
},
{
title: "Following",
to: "/app/following",
},
]
However, I'm getting the following 2 errors:
- Property 'map' does not exist on type 'SubItemsProps'.
- Parameter 'subItem' implicitly has an 'any' type.
Navbar.tsx
type SubItemsProps = {
subItems: DropdownItem[]
}
interface DropdownItem {
subTitle: string,
subLink: string
}
const NavDropdown = ({
title,
subItems
}: {
title: string;
subItems: SubItemsProps;
}) => {
return (
<div>
<div>{title}</div>
<div>
<ul>
{subItems.map(subItem => (
<Link href={subItem.subLink}>
<li>
<span>
{subItem.subTitle}
</span>
</li>
</Link>
))}
</ul>
</div>
</div>
);
};
/* Navbar component */
答案1
得分: 0
类型 SubItemsProps = 下拉项[]
英文:
just edit:
type SubItemsProps = DropdownItem[]
答案2
得分: 0
以下是翻译好的部分:
你可以尝试以下方式来解决这个问题:
<!-- language: lang-js -->
{subItems.subItems.map(subItem => (
<Link href={subItem.subLink}>
<li>
<span>
{subItem.subTitle}
</span>
</li>
</Link>
))}
你定义的类型具有数组作为属性。这就是为什么你必须调用属性来获取数组。
<!-- language: lang-js -->
type SubItemsProps = {
subItems: DropdownItem[]
}
英文:
You might be able to solve the problem the following way:
<!-- language: lang-js -->
{subItems.subItems.map(subItem => (
<Link href={subItem.subLink}>
<li>
<span>
{subItem.subTitle}
</span>
</li>
</Link>
))}
The type which you have defined has the array as attribute. That is why you have to call to the attribute to get the array.
<!-- language: lang-js -->
type SubItemsProps = {
subItems: DropdownItem[]
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论