【问题标题】:Add multiple style properties to a single theme property with Styled Components使用样式化组件将多个样式属性添加到单个主题属性
【发布时间】:2017-09-01 08:11:54
【问题描述】:

我正在为一个新项目使用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;
  ...
`;

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

【问题讨论】:

    标签: css reactjs react-native styled-components


    【解决方案1】:

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

    • 我的组件
      • 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
      },
    });
    

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

    【讨论】:

    • 对不起,我应该说得更清楚。 Styled Components 是一个在 React 组件中使用 CSS 的库。我编辑了问题以链接到库源代码。
    猜你喜欢
    • 2021-07-02
    • 1970-01-01
    • 2019-04-30
    • 2019-07-15
    • 2022-01-17
    • 2021-11-09
    • 1970-01-01
    • 2020-01-16
    • 1970-01-01
    相关资源
    最近更新 更多