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

如何使用emotion-styled实现样式扩展与复用

问题排查与解决方案

你的原有写法逻辑本身符合Emotion的语法规范,没有生效通常是导入路径错误导致的:

  • 请确认css和styled均从@emotion/react(React项目)导入,不要从@emotion/css导入,后者生成的是独立类名字符串,无法直接在styled模板字符串中插值复用。

正确导入后你的原有代码即可正常运行,后续自定义的color: #fff也会自动覆盖公共样式中的黑色配置,符合预期:

import { css, styled } from '@emotion/react'

const commonStyle = css`
  color: #000;
  font-size: 1.6rem;
`;

const commonLink = styled.a`
  ${commonStyle}
`;

const whiteLink = styled.span`
  ${commonStyle}
  color: #fff;
`;

其他复用方案

方案1:基础Styled组件继承

如果需要复用的不仅是样式,还有组件通用属性、逻辑,可以直接定义公共基础组件再扩展:

// 定义基础公共组件,默认使用a标签
const CommonLink = styled.a`
  color: #000;
  font-size: 1.6rem;
`

// 扩展为span标签的白色链接组件,Emotion 11+ 支持直接继承后修改样式
const WhiteLink = styled(CommonLink)`
  color: #fff;
`

// 使用时也可以通过as属性动态切换标签,无需提前定义
<CommonLink as="span" css={{ color: '#fff' }} />

方案2:JS对象形式定义公共样式

适合需要和JS变量联动、动态计算样式的场景:

const commonStyle = {
  color: '#000',
  fontSize: '1.6rem'
}

const commonLink = styled.a(commonStyle)
const whiteLink = styled.span(commonStyle, { color: '#fff' })

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 04:45:03