使用 typescript 定义 InfiniteScroll React 组件的类型

我正在尝试创建一个InfiniteScroll组件以这种方式使用它:


import { getData } from 'api';

import { InfiniteScroll } from 'components';


export const App = () => (

  <InfiniteScroll fetcher={page => getData({page})}>

    {({items}) => items.map(item => <p key={item.id}>{item.name}</p>)}

  </InfiniteScroll>

);

andgetData是一个获取 page 作为参数并返回 Promise 的函数,如下所示:


type Data = {

  id: number;

  name: string;

};


function getData(args: { page: number }): Promise<Data[]> {

  // ...

}

现在我的问题是如何定义InfiniteScroll组件的类型以自动为其 render prop 函数设置类型?


实际上我想items在渲染道具中检索其类型,即道具Data[]中使用的 Promise 的返回值fetcher


我添加了这个codesandbox来处理它:

https://codesandbox.io/s/vigorous-resonance-lj09h ?file=/src/InfiniteScroll.tsx


杨__羊羊
浏览 145回答 1
1回答

qq_花开花谢_0

如果我们可以看到InfiniteScroll组件代码,我们可能可以更好地帮助您,但本质上,您必须执行如下操作。interface Props<T> {&nbsp; fetcher: (page: number) => Promise<T[]>;&nbsp; children: (data: T[]) =>&nbsp; JSX.Element;}export const InfiniteScroll = <T extends unknown>({&nbsp; fetcher,&nbsp; children}: Props<T>) => {&nbsp; const [page, setPage] = useState(1);&nbsp; const [data, setData] = useState<T[] | null>(null);&nbsp; useEffect(() => {&nbsp; &nbsp; fetcher(page).then((res) => {&nbsp; &nbsp; &nbsp; setData(res);&nbsp; &nbsp; });&nbsp; }, [page]);&nbsp;if (!data) return (&nbsp; &nbsp; <p> loading... </p>&nbsp; )&nbsp; return (children(data))};应用程序.tsx:export default function App() {&nbsp; return (&nbsp; &nbsp; <>&nbsp; &nbsp; &nbsp; <InfiniteScroll fetcher={(page: number) => getData(page)}>&nbsp; &nbsp; &nbsp; &nbsp; {(items) => (<>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{(items.map((item,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; index) => <p key={index}> {item.name} </p> ))}&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</>)}&nbsp; &nbsp; &nbsp; </InfiniteScroll>&nbsp; &nbsp; </>&nbsp; );}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript