You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在styled-components定义中继承已有的全局CSS类?

解决方案

方法1:使用attrs绑定默认className(推荐)

styled-components 提供的attrs方法可直接给组件设置默认属性,你可以把固定要加的类名统一配置在这里,同时支持合并外部传入的自定义类名,不会产生冲突:

const Surface = styled.div.attrs(props => ({
  className: `raised bordered ${props.className || ''}`
}))`
  color: darkblue;
  margin: 20px;
`;

配置完成后调用组件无需再重复写className,效果和之前完全一致:

const App = () => (
  <div>
    <Surface>Hello World 1</Surface>
    <Surface>Hello World 2</Surface>
    <Surface>Hello World 3</Surface>
  </div>
);

该方案不需要额外依赖配置,实现效果和你提到的Emotion Composition能力一致。

方法2:通过@apply引入全局样式(需项目配置支持)

如果你的项目已配置PostCSS的@apply插件,也可以直接在样式模板中引入全局类:

const Surface = styled.div`
  @apply raised bordered;
  color: darkblue;
  margin: 20px;
`;

该方案依赖项目的PostCSS配置,兼容性弱于第一种方法。

内容的提问来源于stack exchange,提问作者pyjamas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 18:09:01