Javascript 如何将变量导出到单独的文件?自然反应

Javascript 如何将变量导出到单独的文件?自然反应,javascript,reactjs,react-native,import,export,Javascript,Reactjs,React Native,Import,Export,在我的项目中,我有全局样式的主文件,但我也在单个组件中使用样式。尽管如此,我还是使用相同的变量将字体大小、颜色传递给元素 我不是React方面的专家,但我认为最好将变量移动到单独的文件中,这样就不会重复代码。我怎样才能以正确的方式做到这一点 全局样式: 'use strict'; let React = require('react-native'); let { StyleSheet, } = React; let INIT_COLOR = "#fff"; l

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

我不是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
    },
});  
组件样式:

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;
从“React”导入React;
从“react native”导入{视图、样式表、按钮};
类ActionButton扩展React.Component{
render(){
让INIT_COLOR=“#fff”;
让INIT_FONT_SIZE=16;
返回(
);
}
}
const styles=StyleSheet.create({
按钮容器:{
背景颜色:初始颜色,
fontSize:初始字体大小
}
});
导出默认操作按钮;

例如,您可以在
themes/variables.js
中创建一个文件。大概是这样的:

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

export const fonts = {
  INIT_FONT_SIZE: 16,
};
如果需要,还可以导出每个单独的颜色,但我更喜欢导出颜色对象

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

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;
从“React”导入React;
从“react native”导入{视图、样式表、按钮};
从“主题/变量”导入{颜色、字体};
类ActionButton扩展React.Component{
render(){
返回(
);
}
}
const styles=StyleSheet.create({
按钮容器:{
背景颜色:colors.INIT_COLOR,
fontSize:fonts.INIT_FONT_SIZE
}
});
导出默认操作按钮;

创建一个
styles.js
导出常量INIT_COLOR=“#fff”
。需要它的地方
从“样式”导入{INIT_COLOR}