代码之家  ›  专栏  ›  技术社区  ›  temporary_user_name

如何在react组件的state或props类型中使用泛型类型?

  •  0
  • temporary_user_name  · 技术社区  · 4 年前

    class Fetcher<T> extends React.Component<FetcherProps & { other: T }, FetcherState> {
      constructor(props: FetcherProps & { other: T }) {
        super(props);
      }
    }
    

    { other: T } ,以至于它破坏了可读性。它是用于react render props的--我尝试一般地键入传递给子组件的数据。

    T 当一个组件如此复杂和嵌套时,在props中为它键入什么?

    作为参考,代码实际上如下所示:

    class Fetcher<T> extends React.Component<FetcherProps & { children: (props: {data: T | null, reload: any, error: any, isLoading: boolean}) => React.ReactNode }, FetcherState> {
    
    2 回复  |  直到 4 年前
        1
  •  1
  •   smac89    4 年前

    我会这样做:

    type Props<T> = FetcherProps & { children: (props: {data: T | null, reload: any, error: any, isLoading: boolean}) => React.ReactNode };
    
    class Fetcher<T> extends React.Component<Props<T>, FetcherState> {
      constructor(props: Props<T>) {
        super(props);
      }
    }
    
        2
  •  0
  •   temporary_user_name    4 年前

    解决方案是在泛型组件之外创建泛型类型,并传递泛型类型。所以 FetcherProps & { other: T } ,我用这个:

    type FetcherProps<T> = {
       /* non-generic property types omitted */
       other: T;
    };
    

    class Fetcher<T> extends React.Component<FetcherProps<T>, FetcherState> {