首页 > 解决方案 > 强制儿童在 react-typescript 中输入:类型“元素”不可分配给类型“功能组件”

问题描述

我正在尝试键入一个反应组件,以便它只接受某些类型的孩子。该组件被称为ItemGroup,它应该只接受被称为Submenuor的组件(或组件数组) MenuItem。现在,假设它只能接受一个Submenu作为孩子的单身:

我定义了Submenu组件和道具:

interface SubmenuProps {
  popupId: string;
}

export const Submenu: React.FC<SubmenuProps> = ({ popupId }: SubmenuProps) => {
  return <div>some stuff</div>;
};

现在我定义ItemGroup, 并键入它的子级以仅允许React.ElementTypes 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道具以仅允许Submenus 和/或MenuItems?

标签: reactjstypescriptmaterial-uireact-proptypes

解决方案


推荐阅读