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

使用@mui/system的styled组件调用theme.palette报undefined如何解决

问题原因

你使用@mui/system提供的styled接口时,默认仅内置spacing、shape等基础主题属性,不会自动注入完整的MUI默认配色配置,因此theme.palette为undefined,调用theme.palette.primary.main就会触发报错。

解决方法

你需要主动引入MUI的主题能力,通过ThemeProvider将默认主题注入组件树,修改后的代码如下:

import * as React from 'react';
import { styled } from '@mui/system';
import { ThemeProvider, createTheme } from '@mui/material/styles';

const MyComponent = styled('div')(({theme}) => ({
  color: 'darkslategray',
  padding: theme.spacing(8),
  borderRadius: theme.shape.borderRadius,
  backgroundColor: theme.palette.primary.main,
}));

export default function BasicUsage() {
  // 生成MUI默认主题,可传入自定义配置覆盖默认配色
  const defaultTheme = createTheme();
  return (
    <ThemeProvider theme={defaultTheme}>
      <MyComponent>Styled div</MyComponent>
    </ThemeProvider>
  );
}

轻量替代方案

如果你的组件不需要动态适配主题变化,也可以直接调用默认主题常量,无需包裹ThemeProvider:

import * as React from 'react';
import { styled } from '@mui/system';
import { createTheme } from '@mui/material/styles';

// 直接生成默认主题常量使用
const defaultTheme = createTheme();
const MyComponent = styled('div')(() => ({
  color: 'darkslategray',
  padding: defaultTheme.spacing(8),
  borderRadius: defaultTheme.shape.borderRadius,
  backgroundColor: defaultTheme.palette.primary.main,
}));

export default function BasicUsage() {
  return <MyComponent>Styled div</MyComponent>;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 17:09:04