我在其他地方见过人们使用 React$Element<Type>
所以我假设返回一个数组就像添加 []
一样简单 . 我在这里尝试过:
navbarItems: INavbarItem[];
getNavbarItems(): React$Element<NavbarItem>[] {
return this.navbarItems.map((navbarItem, index) => {
return (
<NavbarItem
key={index}
title={navbarItem.title}
icon={navbarItem.icon}
listPath={navbarItem.listPath}
createPath={navbarItem.createPath}
/>
);
});
}
NavbarItem
class NavbarItem extends Component<Props, any> {
constructor(props: Props) {
super(props);
/* stuff */
}
/* Couple of functions */
render() {
return (
<li>
<DropdownTitle/>
{this.state.open && (
<ul>
<MenuItem>List</MenuItem>
<MenuItem>Create</MenuItem>
</ul>
)}
</li>
);
}
}
但是,当我运行流程时,我收到以下错误:
无法返回this.navbarItems.map(...),因为NavbarItem [1]的静态与数组元素的类型参数ElementType [3]中的NavbarItem [2]不兼容 . [1]类[NavbarItem]扩展Component [2] getNavbarItems():React $ Element <[NavbarItem]> [] [3]声明类型React $ Element <[ElementType]:React $ ElementType>(来自react.js)
上面的[]表示^在错误消息中指向的位置 . 作为流动的新手,我不确定我的组件的静态在这里意味着什么 .
1 回答
首先,你也应该使用React.Element<typeof Component>类型而不是
React$ElementType<T>
,因为后者应该是内部的 .React.Element<typeof Component>
的文档还提示您需要使用typeof operator指定您的意思是NavbarItem
类的类型:(Try)
如果您使用
React$ElementType<T>
,这仍然有效:(Try)