我想要的是在这样的反应功能组件中注释泛型:
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']}/>
}
可以实现吗?如果是,那么该怎么做?
答案 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>
);
}