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

使用@emotion/styled定义样式组件时无法访问theme主题问题求助

问题根因及修复方案

    1. 排查依赖版本一致性
      确保@emotion/react和@emotion/styled的主版本号完全一致,最常见的情况是两个包版本不匹配导致上下文通道不通,升级到同一最新稳定版即可解决绝大多数同类型问题。
    1. 排查多实例冲突
      如果项目依赖复杂,可能存在多个版本的@emotion/react被同时安装,导致ThemeProvider和styled调用的不是同一个上下文实例。可以执行npm ls @emotion/react或者yarn list @emotion/react查看是否存在多版本,存在的话在package.json中用resolutions字段固定版本即可。
    1. 调整Provider嵌套顺序
      @mui/styles的StylesProvider和Emotion的ThemeProvider存在上下文优先级冲突,你可以先尝试移除StylesProvider测试样式是否正常,如果必须保留StylesProvider,调整嵌套顺序,将ThemeProvider放在最外层:
// 修复后的代码示例
import React from 'react';
import styled from '@emotion/styled';
import StylesProvider from '@mui/styles/StylesProvider';
import { ThemeProvider } from '@emotion/react';

const THEME = {
  primary: 'red'
}

const StyledText = styled('p')`
  color: ${({ theme }) => theme.primary};
`;

function App() {
  return (
    <ThemeProvider theme={THEME}>
      <StylesProvider injectFirst>
        <StyledText>test</StyledText>
      </StylesProvider>
    </ThemeProvider>
  );
}

export default App;
    1. 可选兜底方案
      如果以上方案都不生效,可以在styled定义时显式引入useTheme获取主题:
import { useTheme } from '@emotion/react';
const StyledText = styled('p')`
  color: ${() => useTheme().primary};
`;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 16:54:03