[英]React Typescript Union type
我創建了一個 Card 組件,它有兩個變體:Wrapper 和 Dashboard。 每個變體都有不同的道具
export type DashboardProps = {
variant: CardVariant.Dashboard,
primaryText: string,
secondaryText: string,
icon: OverridableComponent<SvgIconTypeMap<{}, "svg">>,
iconColor: string,
}
export type WrapperProps = {
variant: CardVariant.Wrapper,
children: any,
}
export type Props = DashboardProps | WrapperProps;
現在,當我嘗試在組件中使用Props作為類型時,我得到:
Property 'primaryText' does not exist on type 'Props'
Property 'secondaryText' does not exist on type 'Props'
etc..
唯一看起來不錯的鍵是變體,我猜是因為它是兩種類型中唯一的通用鍵。
卡片.tsx
export const Card = ({
variant,
primaryText,
secondaryText,
icon,
iconColor,
children,
}: Props) => {
switch (variant) {
case CardVariant.Wrapper:
return <CardWrapper>{children}</CardWrapper>;
case CardVariant.Dashboard:
return (
<CardDashboard
primaryText={primaryText}
secondaryText={secondaryText}
icon={icon}
iconColor={iconColor}
/>
);
default:
return null;
}
};
最好的方法是什么?
您已經為道具創建了一個可區分的聯合類型。 那么這個呢?
export const Card = (props: Props) => {
switch (props.variant) {
case CardVariant.Wrapper:
return <CardWrapper>{props.children}</CardWrapper>;
case CardVariant.Dashboard:
return (
<CardDashboard
primaryText={props.primaryText}
secondaryText={props.secondaryText}
icon={props.icon}
iconColor={props.iconColor}
/>
);
default:
return null;
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.