如何在react-native上将这两个变量一起导出

时间:2017-12-12 09:39:17

标签: react-native react-native-android react-native-ios native-base

我想为主要颜色制作2个变量,可以在整个应用程序中使用。这是代码:

import React, { Component } from 'react';
import { View, StyleSheet } from 'react-native';

const primary = '#27bcb5';
const secondary = '#ffffff;

如何将这两个变量一起导出以在应用程序组件上使用?

解决方案的问题是:

import  {DefaultStyle}  from './variables';

const screenHeight = Dimensions.get("window").height;

const styles = {
  wrapper: {},
  slide1: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: primary,

它说无法找到变量主

4 个答案:

答案 0 :(得分:2)

您可以执行命名导出。例如。 :

import React, { Component } from 'react';
import { View, StyleSheet } from 'react-native';

const primary = '#27bcb5';
const secondary = '#ffffff';

export { primary, secondary };

之后,您可以通过以下方式导入样式:

import { primary, secondary } from 'YOUR_FILE_PATH' 

答案 1 :(得分:1)

您可以使用以下内容导出它们:

import React, { Component } from 'react';
import { View, StyleSheet } from 'react-native';

const primary = '#27bcb5';
const secondary = '#ffffff';

export const DefaultStyle = {
    primary,
    secondary,
}

所以你可以用它们作为:

import { DefaultStyle } from './default-variables';
console.log(DefaultStyle.primary);
console.log(DefaultStyle.secondary);

答案 2 :(得分:1)

 // Declarations of colors variables     
  const Maincolor ="#333640"
       const Backgroundcolor = "#FFFFFF"
       const Gridcolor = "#A7A9AB" 
        const colors =  // Made to be bind in one because only one export is possiable 
   {
        Maincolor,
        Backgroundcolor,
        Gridcolor,
    }

    export default  colors; // exporting as default 

//在您必须包含

的主代码中
import colors from 'path_of_the_file'
// then in styles use 

style ={{backgroundColor:color.Maincolor}} // example how to use 

答案 3 :(得分:0)

我喜欢做更好的事情,定义一个全局文件,您可以像Moment()时间,设备测量等一样保存。

global.js

const global = {
  PRIMARY: '#27bcb5',
  SECONDARY: '#ffffff,
  DEVICE_MEASURES:{
     WIDTH: Dimensions.get("window").width,
     HEIGHT: Dimensions.get("window").height;
  },
  ...
}

export default global

然后在你的代码中:

import GLOBAL from '(directory)/global'

<View style={{ width: GLOBAL.DEVICE_MEASURES.WIDTH }}>
  <Text style={{ color: GLOBAL.PRIMARY }}>
    sup
  </Text>
</View>

最好有一个全局文件,您可以存储所有应用程序的配置。