如何用TypeScript构建类型正确的React组件映射表?
React组件映射表TS2739错误解决方案
错误原因
你给componentMap定义的值类型为JSX.Element,该类型对应组件渲染后生成的虚拟DOM实例(即<Item1 />的返回值),但你实际存入映射表的是组件本身(组件构造函数/函数组件本体),两者类型不匹配,因此触发类型校验错误。
修复方案
将映射表的值类型替换为React官方提供的通用组件类型ComponentType,该类型兼容函数组件、类组件两种形式:
import type { ComponentType } from 'react' // 可选:定义合法key的联合类型,避免后续传错key type ValidComponentKey = 'Item1' | 'Item2' // 修正后的映射表类型定义 const componentMap: Record<ValidComponentKey, ComponentType<any>> = { "Item1": Item1, "Item2": Item2, }
如果需要严格校验每个组件的入参类型,也可以将any替换为对应组件的props联合类型:
type ItemProps = { props1: string; props2: boolean } | Record<string, never> const componentMap: Record<ValidComponentKey, ComponentType<ItemProps>> = { "Item1": Item1, "Item2": Item2, }
正确使用示例
拿到映射表中的组件后,按普通React组件的方式渲染即可:
function App() { const TargetComponent = componentMap['Item2'] return ( <div> <componentMap.Item1 /> <TargetComponent props1="测试文本" props2={true} /> </div> ) }
内容的提问来源于stack exchange,提问作者Harrison
相关产品推荐
相关产品推荐

