是否可以使用打字稿声明泛型反应功能组件?

时间:2021-06-07 10:24:32

标签: javascript reactjs typescript typescript-generics react-typescript

我想要的是在这样的反应功能组件中注释泛型:

import React, {useEffect, useState} from "react";

interface PaginatedTableProps{
  dataFetcher: (pageNumber: number) => Promise<any>,
  columnNames: string[]
}    

export function PaginatedTable<T>(props: PaginatedTableProps): JSX.Element {
  const [data, setData] = useState<T[]>([]);
  ...
}

然后在另一个功能组件中为 PaginatedTable 功能组件指定具体类型,如下所示:

import React from "react";
import {PaginatedTable} from "./PaginatedTable";
import api from "../../utils/Api";

export function CompanyTable(): JSX.Element{

  interface ConcreteType{
    name: string,
    country: string,
    city: string,
    address: string,
    zipCode: number,
    status: string
  }

  const getData = (pageNumber: number): Promise<any> => {
    return api().getCompanies(pageNumber);
  }

  return (ConcreteType)<PaginatedTable dataFetcher={getData} columnNames={['name', 'country', 'city']}/>
}

可以实现吗?如果是,那么该怎么做?

1 个答案:

答案 0 :(得分:0)

这是一个通用注释功能组件的工作示例。

interface IProps<T> {
  data: T;
}
function Table<T>(props: IProps<T>) {
  return <div>{props.data}</div>
}
export default function App() {
  return (
    <div className="App">
      <Table<number> data={24}/>
    </div>
  );
}