CSS 模块 - 从转换中排除类

Anc*_*nek 12 css reactjs css-modules

我正在使用 CSS 模块,到目前为止一切都很好。

我们开始使用外部 UI 库和我们自己的 UI 库,所以我正在编写这样的组件:

<div className={styles['my-component']}>
   <ExternalUIComponent />
</div>
Run Code Online (Sandbox Code Playgroud)

假设ExternalUIComponent有自己的类,在最终的 CSS 文件中看起来像这样external-ui-component,我如何从我的css文件中调整这个组件样式?下面的例子不起作用:

.my-component {
   font-size: 1em;
}

.my-component .external-ui-component {
   padding: 16px;
   // Some other styling adjustments here
}
Run Code Online (Sandbox Code Playgroud)

xei*_*ton 12

请不要像其他人建议的那样使用内联样式。尽可能远离内联样式,因为它们会导致不必要的重新渲染。

你应该global改用。

.my-component {
    :global {
        .external-ui-component {
           padding: 16px;
           // Some other styling adjustments here
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

https://github.com/css-modules/css-modules#usage-with-preprocessors

此外,我建议使用驼峰式风格名称,这是 css-modules 的首选方式。所以你的班级名称是:.myComponent { ... }

你可以在你的代码中使用它作为

<div className={ styles.myComponent } >
Run Code Online (Sandbox Code Playgroud)

如果要添加更多样式,可以使用array.join(' ')语法。

<div className={ [ styles.myComponent, styles.anotherStyle ].join(' ') } >
Run Code Online (Sandbox Code Playgroud)

这样更干净!


a d*_*ren 7

这是纯 CSS 的较短形式(即不需要预处理器):

.my-component :global .external-ui-component {
   // ...
}
Run Code Online (Sandbox Code Playgroud)