React TypeScript动态组件传递Props遇类型错误,求解决方案
React TypeScript 动态组件循环渲染的类型错误解决方法
问题场景
尝试通过以下代码循环渲染动态组件:
const temp = [{component: Button, props:buttonProps}, {component: Input, props: inputProps},{component: Select, props: selectProps} ] temp.map(cm=>{ return(<div><cm.component {...cm.props}/></div>) })
遇到Prop类型定义错误,错误信息如下:
error: Type '{} | { label?: string | undefined; variant?: "link" | "primary" | "icon-only" | "borderless" | "inline" | "cta" | undefined; size?: "xl" | "lg" | "sm" | "md" | undefined; id?: string | undefined; ... 277 more ...; onTransitionEndCapture?: TransitionEventHandler<...> | undefined; } | ... 7 more ... | { ...; }' is not assignable to type 'never'. The intersection 'IntrinsicAttributes & ButtonProps & TagProps & SwitchProps & ToggleProps & BadgeProps & MessageBlockProps & AvatarProps & CardProps & ModalProps' was reduced to 'never' because property 'variant' has conflicting types in some constituents. Type '{}' is not assignable to type 'never'.
错误原因
TypeScript无法自动推断每个组件对应的props类型,会将所有组件的props做交叉类型,而不同组件的同名属性(比如variant)类型冲突,导致交叉类型变为never。
解决方法
1. 定义精确的联合类型约束数组
给temp数组定义联合类型,让每个项的component和props类型一一绑定:
import { Button, ButtonProps } from '你的组件库路径'; import { Input, InputProps } from '你的组件库路径'; import { Select, SelectProps } from '你的组件库路径'; // 定义组件与对应props的联合类型 type DynamicComponent = | { component: typeof Button; props: ButtonProps } | { component: typeof Input; props: InputProps } | { component: typeof Select; props: SelectProps }; const temp: DynamicComponent[] = [ { component: Button, props: buttonProps }, { component: Input, props: inputProps }, { component: Select, props: selectProps } ];
2. 用泛型函数自动绑定类型
如果不想手动维护联合类型,可通过泛型函数创建数组项,自动关联组件与props类型:
function createDynamicComponent<T extends React.ComponentType<any>>( component: T, props: React.ComponentProps<T> ) { return { component, props }; } const temp = [ createDynamicComponent(Button, buttonProps), createDynamicComponent(Input, inputProps), createDynamicComponent(Select, selectProps) ];
3. 重新渲染组件
完成类型约束后,再执行map渲染,TypeScript就能正确推断每个组件的props类型,错误会自动消失:
temp.map((cm, index) => ( <div key={index}> <cm.component {...cm.props} /> </div> ));
内容的提问来源于stack exchange,提问作者kishore kumar
相关产品推荐
相关产品推荐

