如何将条件道具传递给打字稿中未知类型的反应成分?

时间:2020-05-04 05:55:14

标签: reactjs typescript

我有这个组成部分:

export function Hover(props: PolygonProps) {
   //...
}

 export function Route(props: CenterProps) {
   //...
 }

此枚举:

export enum Highlight {
     HOVER,
     ROUTE,
 }

该对象:

export const HIGHLIGHTS = {
    [Highlight.HOVER]: Hover,
    [Highlight.ROUTE]: Route,
};

此代码在render中:

   let HighlightComponent;
   сonst center = props.center;
   const points = props.points;
   if (highlight !== undefined) {
       HighlightComponent = HIGHLIGHTS[highlight] as React.ComponentType<CenterProps | PolygonProps>;
   }
   const centerProps: CenterProps = { center };
   const polygonProps: PolygonProps = { points };

   return <div>{HighlightComponent && <HighlightComponent />}</div>

问题:如果我不知道类型,该如何传递所需类型的道具(CenterProps或PolygonProps)? 是否适合这种情况的结构?

2 个答案:

答案 0 :(得分:1)

由于您有两个单独的道具,因此您仍然必须检查以查看使用哪个道具。因此,我将删除HIGHLIGHTS常量,只需使用一个开关即可:

   const centerProps: CenterProps = { center: 'someValue' };
   const polygonProps: PolygonProps = { points: 'someOtherValue' };

   let highlightComponent;
   if (highlight !== undefined) {
       switch (highlight) {
           case Highlight.HOVER:
               highlightComponent = <Hover {...polygonProps} />;
               break;
           case Highlight.ROUTE:
               highlightComponent = <Route {...centerProps} />;
               break;
       }
   }

   return <div>{highlightComponent}</div>

另一个选择是像这样定义道具:

const centerProps: CenterProps = { center: 'someValue' };
const polygonProps: PolygonProps = { points: 'someOtherValue' };

export const HIGHLIGHT_PROPS = {
    [Highlight.HOVER]: polygonProps,
    [Highlight.ROUTE]: centerProps,
};

然后:

let HighlightComponent;
let highlightProps;
if (highlight !== undefined) {
    HighlightComponent = HIGHLIGHTS[highlight] as React.ComponentType<CenterProps | PolygonProps>;
    highlightProps = HIGHLIGHT_PROPS[highlight] as CenterProps | PolygonProps;
}

return <div>{HighlightComponent && <HighlightComponent {...highlightProps} />}</div>

答案 1 :(得分:1)

如果我正确理解,您可以执行以下操作:

if (highlight !== undefined) {
    HighlightComponent = HIGHLIGHTS[highlight] === HIGHLIGHTS.HOVER 
       ? <Hover {...polygonProps}/>
       : <Route {...centerProps}/>;
}

return <div>{HighlightComponent && <HighlightComponent />}</div>

但是,这看起来像是代码的味道,因此,我建议您将props更改为HighlightComponent: JSX.Element,然后直接传入相关组件。