首页 > 解决方案 > React TS Generic 组件将通用道具传递给孩子

问题描述

我想创建一个有点像手风琴的 React 组件。它将有孩子,并允许打开/关闭每个。每个孩子也是一个 React 组件,需要来自父母的独特道具,其他孩子可能不会使用。我认为我需要使用泛型来促进这些不同的道具。

我尝试了这个CodeSandbox项目。

标签: reactjstypescript

解决方案


要将组件作为道具传递,请使用ComponentType而不是FC

type SubSectionToggleProps<T> = {
  subSections: ComponentType<SubSectionBaseProps>[];
} & T;

您可能必须对传入的组件进行类型断言

<SubSectionToggle<{ title: string; count: number }>
  title="Hello"
  count={2}
  subSections={[Component1, Component2] as ComponentType<SubSectionBaseProps>[]}
/>

代码沙盒


推荐阅读