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

MUI 5中是否存在与Emotion的css函数等效的功能?

解决方案

  • 你不需要找MUI内部封装的等效方法,直接使用@emotion/css提供的css函数即可,MUI 5底层基于Emotion运行,二者完全兼容,不会出现样式注入冲突、优先级异常等问题。
    使用示例和你提到的Emotion官方用法完全一致:
    import { css, cx } from '@emotion/css'
    
    const headerStyle = css`
      color: blue;
      border-bottom: 1px solid red;
    `;
    
    <Component
      headerClassName={headerStyle}
      footerClassName={css`
        color: gray;
        font-size: 2rem;
      `}
    />
    
  • 如果需要调用MUI的主题变量,可以配合useTheme钩子实现:
    import { css } from '@emotion/css'
    import { useTheme } from '@mui/material/styles'
    
    function Demo() {
      const theme = useTheme()
      const headerStyle = css`
        color: ${theme.palette.primary.main};
        padding: ${theme.spacing(2)};
      `
      return <Component headerClassName={headerStyle} />
    }
    
  • MUI内置的css函数返回SerializedStyles类型,是专门为sx属性、styled组件设计的,定位和你需要的返回类名字符串的能力不同,不需要强行适配。
  • 注意事项:只要保证你安装的@emotion/css版本和MUI依赖的@emotion/react版本保持一致,就不会出现任何兼容问题,使用体验和原生Emotion完全相同,也比已废弃的makeStyles语法更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 09:09:02