reactjs - React TS Generic 组件将通用道具传递给孩子
问题描述
我想创建一个有点像手风琴的 React 组件。它将有孩子,并允许打开/关闭每个。每个孩子也是一个 React 组件,需要来自父母的独特道具,其他孩子可能不会使用。我认为我需要使用泛型来促进这些不同的道具。
我尝试了这个CodeSandbox项目。
解决方案
要将组件作为道具传递,请使用ComponentType
而不是FC
type SubSectionToggleProps<T> = {
subSections: ComponentType<SubSectionBaseProps>[];
} & T;
您可能必须对传入的组件进行类型断言
<SubSectionToggle<{ title: string; count: number }>
title="Hello"
count={2}
subSections={[Component1, Component2] as ComponentType<SubSectionBaseProps>[]}
/>
推荐阅读
- sharepoint - 如何使用 Sharepoint Rest API 更新 sharepoint 中的多个文档元数据
- elasticsearch - Elasticsearch 从索引中删除文档
- visual-studio - Visual Studio 2019 社区版离线安装程序
- mysql - 关于 SQL 内连接
- twitter-bootstrap - Bootstrap 5 类“me-auto”是什么意思
- mysql - 在查询生成器中使用联接查询时,错误显示为字段列表中的未知列
- kubernetes - 入口 - 如何使用基本 URL 分散注意力?
- css - 如何在css中分三个部分制作对角线边框
- python - Tcl 没有正确安装
- python-3.x - 使用 Python 连接时出现雪花角色错误