我正在使用 styled components对于一个新元素,并希望使用库的主题功能。我正在努力弄清楚是否有向一个对象添加多个样式属性的好的或最佳实践方法(即创建一种继承)。想要的是:
// in the theme, define a group of styles for a given component
// e.g. all fonts have a font-family, weight, size, etc
const theme = {
fonts: {
font-family: ...,
font-weight: ...,
font-size: ...,
}
}
// then in my styled component,
// define the multi-line theme, along with component specific styles
// or even override the theme styles
const Header = styled.span`
${props => props.theme.fonts};
text-decoration: underline;
...
`;
现在,我很清楚您需要将主题属性传递给组件上的每个样式。是否有一种模式可以帮助减少我在上面的示例中看到的一些重复代码?
最佳答案
我通常做的是在单独的文件中定义主题样式,例如
- 我的组件
- index.js
- styles.js//<-- 组件的自定义样式
- 主题
- spacing.js//<-- 所有组件的通用样式
- colors.js
- fonts.js
在 spacing.js
里面我会有这样的东西:
const verticalPaddingSmall = {
paddingTop: 5,
paddingBottom: 5,
};
const verticalPaddingMedium = {
paddingTop: 10,
paddingBottom: 10,
};
export default function spacing(size, direction, isPadding) {
// some logic to return the correct object based on the params,
// screen size (tablets vs phones), etc...
return verticalPaddingSmall;
}
显然,该代码是根据我为不同屏幕尺寸等定义的一些配置自动生成的,但最终结果与此类似。
然后在我的自定义组件中导入常用样式,将它们应用于样式并在需要时覆盖它,在 styles.js
上是这样的:
import spacing from 'themes/spacing';
import fonts from 'themes/fonts';
const verticalPaddingSmall = StyleSheet.create({
main: {
...spacing('small', 'vertical', true),
},
title: {
...spacing('xsmall', 'horizontal', false),
...fonts.title,
fontSize: 25, //<--- overwrite default values from title
},
});
我很少覆盖组件上的样式,因为我的常用样式处理表格和手机的不同样式,有点像网络上的媒体查询。
关于css - 使用 Styled Components 将多个样式属性添加到单个主题属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43252766/