[英]Defining type for an InfiniteScroll react component with typescript
I'm trying to create a InfiniteScroll
component to use it in this way:我正在尝试创建一个
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>
);
and getData
is a function that get page as its parameter and returns a Promise like this: getData
是一个获取 page 作为其参数并返回一个 Promise 的函数,如下所示:
type Data = {
id: number;
name: string;
};
function getData(args: { page: number }): Promise<Data[]> {
// ...
}
Now my question is how can I define type for my InfiniteScroll
component to set type for its render prop function automatically?现在我的问题是如何为我的
InfiniteScroll
组件定义类型以自动为其渲染道具功能设置类型?
Actually I want items
in the render props retrieve its type from Data[]
that is return value of the Promise used in fetcher
prop实际上,我希望渲染道具中的
items
从Data[]
中检索其类型,该类型是fetcher
道具中使用的 Promise 的返回值
I added this codesandbox for working on it:我添加了这个代码和框来处理它:
https://codesandbox.io/s/vigorous-resonance-lj09h?file=/src/InfiniteScroll.tsx https://codesandbox.io/s/vigorous-resonance-lj09h?file=/src/InfiniteScroll.tsx
If we could see the InfiniteScroll
component code, we could probably help you better but essentially, you have to do something like below.如果我们可以看到
InfiniteScroll
组件代码,我们可能会更好地帮助您,但本质上,您必须执行以下操作。
interface Props<T> {
fetcher: (page: number) => Promise<T[]>;
children: (data: T[]) => JSX.Element;
}
export const InfiniteScroll = <T extends unknown>({
fetcher,
children
}: Props<T>) => {
const [page, setPage] = useState(1);
const [data, setData] = useState<T[] | null>(null);
useEffect(() => {
fetcher(page).then((res) => {
setData(res);
});
}, [page]);
if (!data) return (
<p> loading... </p>
)
return (children(data))
};
App.tsx:应用程序.tsx:
export default function App() {
return (
<>
<InfiniteScroll fetcher={(page: number) => getData(page)}>
{(items) => (<>
{(items.map((item,
index) => <p key={index}> {item.name} </p> ))}
</>)}
</InfiniteScroll>
</>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.