【问题标题】:What is the best way to add conditional style with styled-components & styled-system?使用样式组件和样式系统添加条件样式的最佳方法是什么?
【发布时间】:2019-08-23 03:40:44
【问题描述】:

我正在尝试使用 styled-system 和 styled-components 创建一个按钮组件。

styled-system 的变体效果很好,但我想知道如何添加条件 css。例如,我正在尝试渲染主块按钮。

const StyledButton = styled(Button)`
  ${props => props.block && css`width: 100%;`
`;

// primary
<StyledButton block variant="primary" />

这按预期工作,但我想知道是否有更好的方法可以使用纯 javascript 以漂亮的方式应用 block

【问题讨论】:

    标签: javascript css reactjs styled-components


    【解决方案1】:

    我认为您可以将您的具体示例缩短如下(您不需要在那里使用css 方法):

    const StyledButton = styled(Button)`
      ${({block}) => block && 'width: 100%;'}
    `;
    

    但总的来说,我相信这是唯一的方法。对我来说看起来并不难看,但是如果您有一些复杂的条件,您可能可以将一些代码移动到具有描述性名称的单独变量或函数中。

    【讨论】:

    • 这在技术上与我分享的解决方案相同。我宁愿使用类名并应用它以使其更像 js 时尚..
    【解决方案2】:

    可以通过这种方式将样式作为 json 对象返回:

    const StyledButton = styled(Button)`
      ${({block}) => block && {width: '100%'}}
    `;
    

    【讨论】:

      【解决方案3】:

      您可以创建一个 mixin 并有条件地添加它。您只需要从 Styled-components 导入 css。例如:

      const buttonWidthMixin = css`
         width: 100%
      `
      

      然后你可以像这样将它添加到按钮中:

      const StyledButton = styled(Button)`
         ${props => props.block && buttonWidthMixin};
      `
      

      现在,如果您将块属性添加到按钮,它会将我们的新 mixin 添加到 css。

      【讨论】:

      • 你忘了在buttonWidthMixin后面加}吗?
      猜你喜欢
      • 2015-03-12
      • 2019-09-26
      • 2020-05-27
      • 2021-07-02
      • 2021-07-07
      • 2014-05-02
      • 2018-09-21
      • 2020-01-12
      • 2019-12-26
      相关资源
      最近更新 更多