reactjs - 强制儿童在 react-typescript 中输入:类型“元素”不可分配给类型“功能组件”
问题描述
我正在尝试键入一个反应组件,以便它只接受某些类型的孩子。该组件被称为ItemGroup
,它应该只接受被称为Submenu
or的组件(或组件数组) MenuItem
。现在,假设它只能接受一个Submenu
作为孩子的单身:
我定义了Submenu
组件和道具:
interface SubmenuProps {
popupId: string;
}
export const Submenu: React.FC<SubmenuProps> = ({ popupId }: SubmenuProps) => {
return <div>some stuff</div>;
};
现在我定义ItemGroup
, 并键入它的子级以仅允许React.ElementType
s ofSubmenuProps
或其数组:
interface ItemGroupProps {
title: string;
children: React.ElementType<SubmenuProps> | React.ElementType<SubmenuProps>[];
}
export const ItemGroup: React.FC<ItemGroupProps> = (props: ItemGroupProps) => {
const { title, children } = props;
return (
<>
<div>{title}</div>
{children}
</>
);
};
我尝试实际使用它:
export default function App() {
return (
<ItemGroup title="something">
<Submenu popupId="123" />
</ItemGroup>
);
}
在使用 时<Submenu />
,我收到一个错误:
Type 'Element' is not assignable to type 'FunctionComponent<SubmenuProps> | ComponentClass<SubmenuProps, any> | ElementType<SubmenuProps>[] | ... 20 more ... | (ElementType<...>[] & ReactPortal)'.
Type 'Element' is not assignable to type 'ElementType<SubmenuProps>[] & ReactPortal'.
Type 'Element' is missing the following properties from type 'ElementType<SubmenuProps>[]': length, pop, push, concat, and 25 more.ts(2322)
App.tsx(14, 3): The expected type comes from property 'children' which is declared here on type 'IntrinsicAttributes & ItemGroupProps & { children?: ReactNode; }'
演示问题的 Codesandbox
我以前做过这种类型的事情,即通过children: React.Elementype<ChildProps>
在父级的 props 接口中使用 a 来强制某些类型的子级。为什么我在这里收到错误。如何键入ItemGroup
'children
道具以仅允许Submenu
s 和/或MenuItem
s?
解决方案
推荐阅读
- web-scraping - 使用 Beautiful Soup 抓取一个人在 Quora 上回答的所有问题
- c++ - 如何正确捕获 Rcpp 异常?
- windows - 什么是“api-ms-win-core-...”?
- javascript - react-paypal-button-v2 付款完成但未收到
- c# - 无法使游戏对象从另一个脚本中移动
- html - 将列表项中的文本与 CSS 对齐
- azure - 使用 ARM 模板生成的主机作为构建代理
- asp.net-core - ServiceStack Nuxt.js SPA 和 ImageSharp.Web 集成
- html - 图片后不显示文字
- .htaccess - mod_rewrite:替换下划线导致无限循环