【问题标题】:How to globally prefix all css rules generated by styled-components 5.3.5 with a parent class如何使用父类全局为 styled-components 5.3.5 生成的所有 CSS 规则添加前缀
【发布时间】:2022-06-22 01:26:24
【问题描述】:

我的应用将被加载到具有特定类 (.my-class) 的 div 中。

有没有办法让 styled-components 生成的所有样式都在前面加上 .my-class。

所以通常你可能会有类似的输出

.cuetwY { color: blue; }

会变成

.my-class .cuetwY { color: blue; }

babel-plugin-styled-components-css-namespacestylis-plugin-extra-scope 我都试过了,但似乎都不适用于新版本的样式组件,而旧版本的 sc 不适用于 React 18。

【问题讨论】:

    标签: css reactjs babeljs styled-components


    【解决方案1】:

    如果我理解正确,您想使用 styled-components 在组件中设置自己的类/类。在这种情况下,您可以使用 attrs 方法设置自定义类。

    这是一种可链接的方法,将一些道具附加到样式组件。第一个也是唯一的参数是一个对象,它将被合并到组件的其余部分中。 attrs 对象接受以下值:documentation

    import styled from "styled-components";
    
    const Style = styled.button.attrs(() => ({
      className: "my-class"
    }))`
      background-color: grey;
      color: white;
      padding: 1rem 2rem;
    `;
    
    export const Button = () => {
      return <Style>Click me</Style>;
    };
    

    【讨论】:

      猜你喜欢
      • 2016-01-19
      • 1970-01-01
      • 1970-01-01
      • 2019-12-22
      • 1970-01-01
      • 2019-02-22
      • 2017-11-18
      • 2010-10-27
      • 1970-01-01
      相关资源
      最近更新 更多