[英]How to export variables to separate file? React Native
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.
但是,我使用相同的变量将字体大小,颜色传递给元素。
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. 我不是React方面的专家,但我认为将变量移至单独的文件而不重复代码会很好。 How can I do this in a proper way?
我如何以适当的方式做到这一点?
Global styles: 整体风格:
'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
},
});
Component styles: 组件样式:
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;
You can just create a file into themes/variables.js
for example. 例如,您可以仅将文件创建到
themes/variables.js
中。 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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.