首页 > 解决方案 > 如何正确包装和导出也具有组件作为属性的 React 组件

问题描述

我正在构建一个 React Native 应用程序,并且一直在包装来自各种库的一些组件,以便使用明暗模式正确地对它们进行主题化。

通常我会像这样包装和导出它:

import * as React from 'react';
import { Text as _Text, TextProps as _TextProps } from 'react-native-elements';

import { ThemeProps, useThemeColor } from './Theme';

export type TextProps = ThemeProps & _TextProps & { children: any };

export function Text(props: TextProps) {
  const { style, lightColor, darkColor, ...otherProps } = props;
  const color = useThemeColor({ light: lightColor, dark: darkColor }, 'text');

  return <_Text style={[{ color }, style]} {...otherProps} />;
}

但是,我正在尝试Card从具有一些子组件的 react-native-elements 包装组件。以下是在任何包装之前如何正常使用组件的示例Card(取自https://reactnativeelements.com/docs/card/):

<Card>
  <Card.Title>CARD WITH DIVIDER</Card.Title>
  <Card.Divider/>
  {
    users.map((u, i) => {
      return (
        <View key={i} style={styles.user}>
          <Image
            style={styles.image}
            resizeMode="cover"
            source={{ uri: u.avatar }}
          />
          <Text style={styles.name}>{u.name}</Text>
        </View>
      );
    })
  }
</Card>

那么,我如何包装这个Card组件,并希望它的所有子组件,比如Card.TitleCard.Divider它们仍然可以以类似的方式访问?

标签: reactjstypescriptreact-nativereact-native-elements

解决方案


推荐阅读