首页 > 解决方案 > React-Native 将类型化类包装到功能组件中以进行样式设置

问题描述

我将组件包装成功能组件以执行一致的样式。这在大多数情况下工作得很好,但是如果包装的组件在其属性中具有泛型,事情就会变得有点混乱。具体来说,我无法围绕FlatList组件以及如何定义ItemT.

  type Props<ItemT> = React.ComponentProps<typeof FlatList> & {
     theme: Theme
  }

  const MyFlatList = <ItemT extends {}>(props: Props<ItemT>) => {
     const { theme } = props

     return <FlatList {...props} contentContainerStyle={{ backgroundColor: theme.colors.background }} />
  }

  export default withTheme(MyFlatList)

这基本上符合react-native-paper这里推荐的内容https://callstack.github.io/react-native-paper/theming.html#customizing-all-instances-of-a-component。虽然编译没有错误,但如果我在我的代码中使用这个组件,类型信息就会丢失。

   <MyFlatList
      data={items}
      keyExtractor={item => item.id}
      renderItem={({ item }) => renderItem(item)}
    />

item这种情况下是类型unknown,而简单来说FlatList,类型是正确派生的。我想问题是ItemT extends {},但我还没有找到任何其他方法让调用者定义ItemT. 任何想法?

标签: typescriptreact-nativetypescript-generics

解决方案


推荐阅读