问题
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. 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;
回答1:
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;
来源:https://stackoverflow.com/questions/49280777/how-to-export-variables-to-separate-file-react-native