使用带有FlatList的打字稿的高阶组件的问题

时间:2020-08-31 21:34:42

标签: typescript react-native react-native-flatlist high-order-component

问题:

我需要使用可以推断devFlatList的类型的高阶组件。

typescript

我该怎么做而没有错误?

说明:

我决定创建一个组件,并将其自定义注入<CustomFlatList<MyObject> // props /> 注入应用程序的任何Props中。

我认为高阶组件最适合这种情况。

FlatList

但是,并非如此:一切正常,{strong>除与// my code so far interface InjectedProps { customProps: any; } export const withCustomProps = <T extends object>(Component: React.ComponentType<T>): React.FC<T & InjectedProps> => ({ customProps, ...props }: InjectedProps) => { // a bit of more logic return <Component {...(props as T)} />; }; export const CustomFlatList = withCustomProps(FlatList); 一起使用。当我尝试强烈键入我的typescript以推断其他道具方法(例如FlatList)时,我遇到了一个错误:

renderItem

目前,我别无选择,只能使用<CustomFlatList // works // props /> <CustomFlatList<MyObject> // Expected 0 type arguments, but got 1 // props /> 作为渲染方法的定义。

any

我还尝试模仿renderItem={ ({ item }: { item: any }) => {//whatever} } 的语法-使用两个嵌套的泛型类型(FlatListT

ItemT
// React definition of FlatList
export class FlatList<ItemT = any> extends React.Component<FlatListProps<ItemT>>

但是我还有另一个// My buggy code export const withCustomProps = <T extends object, ItemT>(Component: React.ComponentType<T<ItemT>>): React.FC<T & InjectedProps> => ({ customProps, ...props }: InjectedProps) => { return <Component {...(props as T)} />; }; export const CustomFlatList = withCustomProps(FlatList); 错误:

typescript

1 个答案:

答案 0 :(得分:-1)

也许您正在尝试重新发明轮子? 请看一下recompose的实现: https://github.com/acdlite/recompose/blob/7d5adf7f49b21e3693f7d631551d282e5c8ef820/src/packages/recompose/withProps.js

和输入: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/3816f1d08454135487e36ff5aeb1bc4e51ff52ca/types/recompose/index.d.ts#L71

很久以前,React社区开始转向功能组件和挂钩。您如何看待基于功能组件的简化实现?

const FlatList = (props: Props) => <div />;

const CustomList = (props: Props & InjectedProps) => <FlatList {...props} />;

const a = <FlatList foo={123} />;
const b = <CustomList foo={123} bar={456} />;

https://www.typescriptlang.org/play?target=7#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wG4Aoc4AOxiSk3STgAUcwBnOAb3Ln7iYIEAFxxqAVxAAjehQC+lGnQZM4ASWoArJBiQATNhE48+A6SihjJMueUXk0Eah3gAxADYoYAGWCu4AF44AAowdg4xI04ASiCAPjgAHn1gADc4AHp4ikdnAIBhCVdcPwDgsIioiLgAMg1tXTpDCLjAxKTPbzL4bgA6AfDjDnksnMonF3gUIOSu338sYUDuAEYAJgBmUeyKSYDpWaSikpAewWW1rdGLKBWAFgBWADYd8aA