【问题标题】:How to import a reusable component from theme folder in react native?react-native - 如何从主题文件夹中导入可重用组件?
【发布时间】:2020-07-22 22:04:54
【问题描述】:

我想从主题文件夹中导入一个可重用的 Button 组件。

这是Button组件的路径:

\app\theme\components\Button.ts

这是Button.ts的代码

import { typography } from "theme/typography";
import { ButtonProps } from "react-native-elements";

export const Button = {
titleStyle: {
    fontSize: typography.size,
    fontFamily: typography.primaryMedium,
    lineHeight: typography.size,
    letterSpacing: 0,
    marginHorizontal: typography.size
},
containerStyle: {
    borderRadius: typography.size * 2 + typography.size * 2
},
buttonStyle: {
    borderRadius: typography.size * 2 + typography.size
}
} as ButtonProps

这是我要导入的组件:organizationdetails-screen.tsx

它的路径是\app\screens\superadmin-screens\organizationdetails-screen.tsx

我正在尝试像这样导入按钮

import { Button } from '../../theme/components/Button';

但是我收到了这个错误

我正在使用这样的按钮:

<Button
     title="Add User"
     onPress={() => this.props.navigation.navigate('AddNewUser')}
/>

当我将鼠标悬停在 Visual Studio Code 中的按钮上时,它会显示以下错误:

如何导入这个可重复使用的按钮?

【问题讨论】:

  • 从'../../theme/components/Button'导入按钮作为导入按钮;移除 {}
  • 我试过了,但它不起作用。它显示了这个错误i.ibb.co/ZN77T4S/error3.jpg
  • 您的Button 不是组件。 export const Button = { titleStyle: { fontSize: typography.size, 位看起来像一个样式对象:您需要从您的Button 返回一个反应元素,例如export const Button = () =&gt; &lt;Text&gt;I'm not a button&lt;/Text&gt; - 当然使用您想要的道具、样式和元素。

标签: android typescript react-native


【解决方案1】:

您似乎只在\app\theme\components\Button.ts 中定义了按钮道具,并试图将它们用作组件。这行不通。

在你的 '\app\theme\components\Button.tsx' 中试试这个:

import { StyleSheet } from 'react-native';
import { Button as RNButton, ButtonProps } from 'react-native-elements`;
import { typography } from "theme/typography";


const styles = StyleSheet.create({
  titleStyle: {
    fontSize: typography.size,
    fontFamily: typography.primaryMedium,
    lineHeight: typography.size,
    letterSpacing: 0,
    marginHorizontal: typography.size
  },
  containerStyle: {
    borderRadius: typography.size * 2 + typography.size * 2
  },
  buttonStyle: {
    borderRadius: typography.size * 2 + typography.size
  }
});


export const Button = (props: ButtonProps) => (
 <RNButton
  titleStyle={styles.titleStyle}
  containerStyle={styles.containerStyle},
  buttonStyle={styles.buttonStyle}
  {...props}
);

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-16
  • 1970-01-01
  • 2020-09-20
  • 2018-08-22
  • 2019-06-21
  • 2018-11-26
相关资源
最近更新 更多