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

如何基于MUI Toolpad Core主题切换Logo?useTheme方法失效求助

解决MUI Toolpad Core主题切换时Logo不切换的问题

问题原因

你当前的branding.logo是静态<img>元素,若直接在App组件外部使用useTheme(),会因不在MUI主题上下文环境中,导致获取的theme.palette.mode始终为默认的light;同时静态元素无法随主题变化自动更新。

解决方案

1. 创建动态Logo组件

单独编写响应主题变化的Logo组件,在组件内部获取当前主题模式并切换图片源:

import { useTheme } from '@mui/material/styles';
import logo from './assets/logo.png';
import logoDark from './assets/logo_white.png';

const DynamicLogo = () => {
  const theme = useTheme();
  return <img src={theme.palette.mode === 'dark' ? logoDark : logo} alt="Logo" />;
};

2. 更新branding配置

将原来静态的logo替换为上述动态组件:

// 定义branding对象
const branding = {
  logo: <DynamicLogo />,
  title: '',
  homeUrl: '/',
};

3. 确保主题切换逻辑生效

确认主题配置和切换功能正常:

  • 你的dhandhoTheme配置中colorSchemes: { light: true, dark: true }和colorSchemeSelector: 'class'是正确的,MUI会通过body上的CSS类切换主题。
  • 确保存在主题切换交互(比如添加ColorSchemeToggle组件,或使用Toolpad内置主题切换功能),否则主题会一直停留在默认的light模式。

完整修改后的代码示例

import { AppProvider } from "@toolpad/core";
import React from "react";
import { Outlet } from "react-router-dom";
import { ConnectWithoutContact, ViewList } from '@mui/icons-material';
import DashboardIcon from '@mui/icons-material/Dashboard';
import LayersIcon from '@mui/icons-material/Layers';
import SettingsIcon from '@mui/icons-material/Settings';
import logo from './assets/logo.png';
import logoDark from './assets/logo_white.png';
import { extendTheme, useTheme } from "@mui/material";
import { useAuth } from "./components/Auth/AuthProvider";

const NAVIGATION = [ // 你的导航配置
];

const colors = {
    // 你的自定义颜色
};

// 定义主题
const dhandhoTheme = extendTheme({
    colorSchemes: { light: true, dark: true },
    colorSchemeSelector: 'class',
    customColors: colors,
    palette: {
        primary: {
            main: '#20A4F3',
        },
        success: {
            main: '#2EEE80',
        },
        // 其他颜色配置
    },
});

// 动态Logo组件
const DynamicLogo = () => {
  const theme = useTheme();
  return <img src={theme.palette.mode === 'dark' ? logoDark : logo} alt="Logo" />;
};

// 定义branding对象
const branding = {
    logo: <DynamicLogo />,
    title: '',
    homeUrl: '/',
};

export default function App() {
    const { session, authentication } = useAuth();
    return (
        <AppProvider
            navigation={NAVIGATION}
            branding={branding}
            theme={dhandhoTheme}
            session={session}
            authentication={authentication}
        >
            <Outlet />
        </AppProvider>
    );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 10:25:22