【问题标题】:How to add multiple styles based on property with styled-components?如何基于带有样式组件的属性添加多种样式?
【发布时间】:2018-04-26 19:48:40
【问题描述】:

在 CSS/LESS 中我会这样做:

.button {
    &:active, .active {
        background-color: #393939;
        border-color: #2F2F2F;
        box-shadow: inset 0 0 0 1px #3D3D3D,
            inset 0 2px 0 #323232;

    }
}

:active 是我的按钮在被点击时的样式,.active 是我在按钮处于活动状态时添加 的类(用于可切换按钮)。

styled-components 我现在有这个:

import styled from 'styled-components';

export default styled.button`
    width: 32px;
    height: 32px;
    border-radius: 5px;
    background-color: #535353;
    border: 1px solid transparent;
    cursor: pointer;
    outline: none;
    padding: 4px;

    &:active, /* what to do here?? */ {
        background-color: #393939;
        border-color: #2F2F2F;
        box-shadow: inset 0 0 0 1px #3D3D3D,
            inset 0 2px 0 #323232;

    }
`

但我不知道如何根据某些属性重用所有这些 :active 样式。我知道我可以使用 ${props => prop.active} 访问道具,但我不知道如何在不重复所有这些样式的情况下重复使用该样式块。

我该怎么做?

【问题讨论】:

    标签: css reactjs styled-components


    【解决方案1】:

    如果你想分享一些样式,你可以简单地将它移动到一个你在两个地方都使用的变量中:

    import styled, { css } from 'styled-components'
    
    const activeStyles = `
       background-color: #393939;
        border-color: #2F2F2F;
        box-shadow: inset 0 0 0 1px #3D3D3D,
            inset 0 2px 0 #323232;
    `
    
    export default styled.button`
      width: 32px;
      height: 32px;
      border-radius: 5px;
      background-color: #535353;
      border: 1px solid transparent;
      cursor: pointer;
      outline: none;
      padding: 4px;
    
      &:active {
        ${activeStyles}
      }
    
      ${props => props.active ? css`${activeStyles}` : ''}
    `
    

    【讨论】:

    • 谢谢!也许提到您还需要从 styled-components 导入 cssimport styled, { css } from 'styled-components'
    • 如果您也需要为 activeStyles 使用主题和道具怎么办?
    【解决方案2】:

    您可以这样做,而不是使用模板文字:

    const Heading = styled.div([], props => ({
      backgroundColor: 'red',
    
      ...(props.isOpen && {
        backgroundColor: 'blue', 
        color: 'white',
        // ...some other styles
      })
    }));
    

    【讨论】:

      猜你喜欢
      • 2019-04-30
      • 2021-10-03
      • 1970-01-01
      • 2017-09-01
      • 2014-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多