如何将变量导出到单独的文件?反应本机 [英] How to export variables to separate file? React Native

查看:55
本文介绍了如何将变量导出到单独的文件?反应本机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,我有带有全局样式的主文件,但是我在单个组件中使用样式.但是,我使用相同的变量将字体大小,颜色传递给元素.

In my project I have main file with global styles but also I use styles in a individual components. Nonetheless I use the same variables to pass font-size, colours to elements.

我不是React方面的专家,但是我认为将变量移到单独的文件中而不重复代码会很好.我如何以适当的方式做到这一点?

I'm not an expert in React but I think that will be nice to move variables to separate file to don't repeat the code. How can I do this in a proper way?

全局样式:

'use strict';

  let React = require('react-native');

  let {
    StyleSheet,
  } = React;

  let INIT_COLOR = "#fff";
  let INIT_FONT_SIZE = 16; 


  module.exports = StyleSheet.create({
    container: {
        backgroundColor: INIT_COLOR,
        fontSize: INIT_FONT_SIZE
    },
});  

组件样式:

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

class ActionButton extends React.Component {

 render() {
   let INIT_COLOR = "#fff";
   let INIT_FONT_SIZE = 16;

  return (
    <View style={styles.buttonContainer}>
        <Button
          onPress={this.props.onPress}
        />
    </View>
   );
 }
}

const styles = StyleSheet.create({
    buttonContainer: {
      backgroundColor: INIT_COLOR,
      fontSize: INIT_FONT_SIZE
    }
   });

export default ActionButton;

推荐答案

例如,您可以将文件创建到 themes/variables.js 中.像这样的东西:

You can just create a file into themes/variables.js for example. something like this:

export const colors = {
  INIT_COLOR: "#fff",
  //... more colors here
};

export const fonts = {
  INIT_FONT_SIZE: 16,
};

如果需要,您还可以导出每种颜色,但是我更喜欢导出颜色对象.

You can also export each individual color if you want, but I'd prefer to export an object of colors.

然后,您可以将该文件导入组件中:

Then you can import that file in your components:

import React from 'react';
import { View, StyleSheet, Button} from 'react-native';
import { colors, fonts } from 'theme/variables';

class ActionButton extends React.Component {

 render() {
  return (
    <View style={styles.buttonContainer}>
        <Button
          onPress={this.props.onPress}
        />
    </View>
   );
 }
}

const styles = StyleSheet.create({
    buttonContainer: {
      backgroundColor: colors.INIT_COLOR,
      fontSize: fonts.INIT_FONT_SIZE
    }
});

export default ActionButton;

这篇关于如何将变量导出到单独的文件?反应本机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆