【问题标题】:How to extend(inherit) a global CSS class from within a styled-components如何从样式组件中扩展(继承)全局 CSS 类
【发布时间】:2018-12-03 15:17:51
【问题描述】:

是否可以将全局 CSS 类注入 styled-component

类似于在 LESS 中使用 &:extend@extend 在 SASS 中扩展。

此代码不适用于globalCSS 样式:

const extendedComponent = styled.div`
  &:extend(.globalClass) // I want this component to inherit all styles of .globalaCSS
  .otherStyles {
    ...
  }
`

globalClass 在内联使用时会退出,甚至会应用样式:

extendedComponent(className="globalCSS)

【问题讨论】:

    标签: css reactjs styled-components


    【解决方案1】:

    您可以将“类名”添加到您的元素中, 但如果你真的想继承或扩展。

    以他们的例子作为参考:

    const Button = styled.button`
      color: palevioletred;
      font-size: 1em;
      margin: 1em;
      padding: 0.25em 1em;
      border: 2px solid palevioletred;
      border-radius: 3px;
    `;
    
    // We're extending Button with some extra styles
    const TomatoButton = Button.extend`
      color: tomato;
      border-color: tomato;
    `;
    

    文档链接: https://www.styled-components.com/docs/basics#extending-styles

    【讨论】:

    • 我不确定这是否能解决问题?我刚刚遇到了同样的问题。我是样式化组件的新手。在 Bootstrap 中,您可以使用诸如“mt-2”之类的间距类型类,这意味着“间距的前 2 个单位”。这些间距单位根据媒体查询甚至您自己的 sass 变量修改而有所不同。您可以在 sass 中创建一个类并执行类似“.new-class { @extend .mt-2 : ... my stuff ... } 之类的操作。我认为这就是这个人要问的?
    【解决方案2】:

    使用attrshttps://styled-components.com/docs/api#attrs

    const extendedComponent = styled.div.attrs({
        className: 'globalCssClassThatIWantToExtend'
    })`
        .otherStyles {
            /*...*/
        }
    `;
    

    attrs 函数也可以接受一个 props 函数:

    .attrs(props => ({
        /*...*/
    }))
    

    【讨论】:

      猜你喜欢
      • 2017-10-19
      • 2011-04-06
      • 2021-10-09
      • 1970-01-01
      • 2023-03-31
      • 2018-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多