【问题标题】:Reuse a 'mixin' with Styled Components across different files?跨不同文件重用带有样式组件的“混合”?
【发布时间】:2018-10-18 03:24:53
【问题描述】:

如何在不同的文件中重复使用带有样式组件的样式集合?

使用 SASS,我可以像这样定义和使用 mixin:

@mixin section( $radius:4px ) {
  border-radius: $radius;
  background: white;
}

.box { @include section(); }

使用样式化组件,您可以扩展样式,但这意味着我需要将该组件导入每个页面。与 ThemeProvider 随处可用的变量相比,这非常麻烦。

https://www.styled-components.com/docs/basics#extending-styles

【问题讨论】:

    标签: styled-components


    【解决方案1】:

    只是补充@Evanss 的答案

    您可以通过以下方式使 mixin 成为一个函数(如在 OP 中):

    const theme = {
     sectionMixin: (radius) => `border-radius: ${radius};`
    }
    

    然后像这样使用它:

    const Button = styled.button`
     ${props => props.theme.sectionMixin('3px')}
    `
    

    或者只是:

    const Button = styled.button`
     ${({ theme }) => theme.sectionMixin('3px')}
    `
    

    【讨论】:

      【解决方案2】:

      您可以创建具有多个 CSS 规则的字符串并将其传递给 ThemeProvider。

      const theme = {
        sectionMixin:
          'background: white; border-radius: 5px; border: 1px solid blue;',
      }
      
      
      <ThemeProvider theme={theme}>
      

      【讨论】:

      • 有没有其他方法可以使用现有的混音?
      • 为什么不包含传递给原始 mixin 的 radius 变量?
      • @vsync 检查我对您问题的回答 :)
      猜你喜欢
      • 2018-04-20
      • 1970-01-01
      • 2018-10-16
      • 2021-02-19
      • 2018-10-19
      • 1970-01-01
      • 2020-10-18
      • 2020-01-22
      • 1970-01-01
      相关资源
      最近更新 更多