1

我正在为一个新项目使用样式组件,并希望使用库的主题功能。我正在努力弄清楚是否存在向一个对象添加多个样式属性的良好或最佳实践方法(即,创建一种继承)。想要的是:

// 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;
  ...
`;

现在,对我来说很明显,您需要将主题属性传递给组件上的每个样式。有没有一种模式可以帮助减少上面示例中出现的一些重复代码?

4

1 回答 1

1

我通常做的是在单独的文件中定义主题样式,例如

  • 我的组件
    • index.js
    • styles.js //<-- 组件的自定义样式
  • 主题
    • spacing.js // <-- 所有组件的通用样式
    • 颜色.js
    • 字体.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
  },
});

我很少覆盖组件的样式,因为我常用的样式处理表格和电话的不同样式,有点像网络上的媒体查询。

于 2017-04-06T16:50:56.460 回答