我假设您因为样式使用了很多字符串。我做同样的事情,我尝试将最大数量的样式信息提取到具有不同样式文件的单独文件夹中。不仅是变量,还有通常分组的样式。
例如:
const styleVariables = {
// Fonts
baseFontSize: 16,
largeFontSize: 24,
// Icons
smallIconSize: 24,
mediumIconSize: 36,
// Colors
mainColor: '#e85e45',
secondaryColor: '#a0c5d8',
offWhite: '#f4f4f4',
darkColor: '#404040',
// Dimensions
headerHeight: 70,
shadowSize: 6
};
export default styleVariables;
我在其他相关信息分组的样式文件中引用我的变量:
/* presentation.js */
import variables from './variables';
export const shadow = {
shadowColor: variables.darkColor,
shadowRadius: variables.shadowSize,
shadowOpacity: 0.35,
shadowOffset: {width: 0, height: 0}
};
export const centered = {
alignItems: 'center'
justifyContent: 'center'
}
然后在我的组件中,我只引用我的样式:
import variables from './../styles/variables';
import {centered, shadow} from './../styles/presentation';
class RoundButton extends React.PureComponent {
render() {
return (
<View style={styles.button}>
{this.props.children}
</View>
);
}
}
const styles = StyleSheet.create({
button: {
width: variables.buttonSize,
height: variables.buttonSize,
borderRadius: variables.buttonSize / 2,
...centered
...shadow
}
对于文本样式和常见的演示文稿,这确实减少了代码,并允许在一个地方轻松修改。