【问题标题】:Pass flow type to react component将流类型传递给反应组件
【发布时间】:2021-04-05 14:06:14
【问题描述】:

我有一个组件使用来自外部项目的另一个组件。如何在没有重复类型的外部组件中生成流类型?

例如:

import {ExternalComponent} from '@npm-component/another-component';

type CurrentComponentType = {|
  data: {
    count: number,
    items: [{code: string, descroption: string}]
  }
|};

export CurrentComponent = ({data}: CurrentComponentType) => {
const onClick = () => {}
return <ExternalComponent data={data} onClick={onClick}/>;
}

目前,我在外部组件中复制流类型

type ExternalComponentType = {|
  data: {
    count: number,
    items: [{code: string, descroption: string}]
  }
|};

export ExternalComponent = ({data}: ExternalComponent) => {
const onClick = () => {}
return data.items.map(({code}) => <span>{code}</span>);
}

例如我想要什么

type ExternalComponentType = GenerateTypeHere;

export ExternalComponent = ({data}: ExternalComponent) => {
const onClick = () => {}
return data.items.map(({code}) => <span>{code}</span>);
}

【问题讨论】:

    标签: javascript reactjs generics flowtype definition


    【解决方案1】:

    这取决于您要从中导入的库是否实际导出了流类型。为了回答这个问题,我们假设它确实如此。

    如果他们这样做了,他们的代码会是这样的

    // @flow
    export type ComponentProps = {};
    
    export default Component = () => ...
    

    然后在你的代码中你可以像这样导入它

    // @flow
    import Component, { type ComponentProps } from '@npm-component/another-component';
    // Or if you want to import just the type on a line
    import type { ComponentProps } from '@npm-component/another-component';
    
    type CurrentComponentType = {
      ...ComponentProps,
      a: string, // If you want to extend the props with more functionality
    };
    
    export const CurrentComponent = ({ data }: CurrentComponentType) => {
      const onClick = () => {}
      return <ExternalComponent data={data} onClick={onClick}/>;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-11-01
      • 1970-01-01
      • 2019-01-02
      • 1970-01-01
      • 1970-01-01
      • 2019-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多