簡體   English   中英

是否可以使用 typescript 聲明 generics 反應功能組件?

[英]Is it possible to declare generics react functional components using 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']}/>
}

是否可以實施? 如果是,那么該怎么做?

這是通用注釋功能組件的工作示例。

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>
  );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM