我正在使用CSS模块,到目前为止一切都很好。
我们开始使用外部UI库和我们自己的UI库,所以我编写了这样的组件:
<div className={styles['my-component']}>
<ExternalUIComponent />
</div>
假设ExternalUIComponent
有自己的类,在最终的CSS文件中看起来像这个external-ui-component
,我如何从我的css
文件中调整这个组件样式?以下示例不起作用:
.my-component {
font-size: 1em;
}
.my-component .external-ui-component {
padding: 16px;
// Some other styling adjustments here
}
请不要按照其他人的建议使用内联样式。尽可能远离内联样式,因为它们可能会导致不必要的重新渲染。
您应该改用global
。
.my-component {
:global {
.external-ui-component {
padding: 16px;
// Some other styling adjustments here
}
}
}
https://github.com/css-modules/css-modules#usage-with-preprocessors
另外,我建议使用驼峰大小写样式名称,这是css模块的首选方式。 所以你的类名将是:.myComponent { ... }
您可以在代码中将其用作
<div className={ styles.myComponent } >
如果要添加更多样式,可以使用array.join(' ')
语法。
<div className={ [ styles.myComponent, styles.anotherStyle ].join(' ') } >
这更干净!
这是纯CSS中的较短形式(即不需要预处理器(:
.my-component :global .external-ui-component {
// ...
}
您是否尝试过该组件的内联样式?
https://reactjs.org/docs/dom-elements.html#style
const divStyle = {
color: 'blue',
backgroundImage: 'url(' + imgUrl + ')',
};
function HelloWorldComponent() {
return <div style={divStyle}>Hello World!</div>;
}