使用Styled Components将多个样式属性添加到单个主题属性

时间:2017-04-06 10:38:08

标签: css reactjs react-native styled-components

我使用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;
  ...
`;

现在,我只能明白你需要将theme属性传递给组件上的每个样式。是否有一种模式可以帮助减少上面例子中看到的一些重复代码?

1 个答案:

答案 0 :(得分:1)

What I usually do is to define the theme styles in a separate files, for example

  • MyComponent
    • index.js
    • styles.js //<-- Custom styles for component
  • theme
    • spacing.js // <-- Common styles for all components
    • colors.js
    • fonts.js

Inside spacing.js I would have something like this:

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;
}

Obviously, that code is automatically generated based on some configurations I define for different screen sizes and so on, but the end result is something similar to that.

Then in my custom component I import the common styles, apply them to the styles and overwrite if needed it, something like this on 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
  },
});

I rarely overwrite styles on components, because my common styles handle different styles for tables and phones, kinda like media queries on the web.