如何将变量导出到单独的文件?反应本机

Ita*_*lik 6 javascript import export reactjs react-native

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

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

整体风格:

'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
    },
});  
Run Code Online (Sandbox Code Playgroud)

组件样式:

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;
Run Code Online (Sandbox Code Playgroud)

Cry*_*fel 7

例如,您可以仅创建一个文件themes/variables.js。像这样的东西:

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

export const fonts = {
  INIT_FONT_SIZE: 16,
};
Run Code Online (Sandbox Code Playgroud)

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

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

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;
Run Code Online (Sandbox Code Playgroud)