跳转至

CompThemeProvider 主题提供者组件文档

组件概述

CompThemeProvider 是一个 Ant Design 主题配置的上下文提供者组件,用于在整个应用中统一管理和传递主题配置。

核心功能

  • 主题配置传递:通过 React Context 传递 Ant Design 主题配置
  • 算法支持:内置支持亮色/暗色主题算法
  • CSS 变量:默认启用 CSS 变量模式
  • 便捷钩子:提供 useMiThemeConfig 钩子获取当前主题配置

组件组成

1. CompThemeProvider

主题配置的容器组件,用于包裹需要应用主题的子组件。

Props: | 属性名 | 类型 | 必填 | 描述 | |--------|------|------|------| | children | React.ReactNode | 是 | 子组件 |

2. MiThemeProvider

主题上下文提供者,用于在应用顶层设置主题配置。

3. useMiThemeConfig

自定义 Hook,用于在子组件中获取当前主题配置。

使用示例

基本用法

import { CompThemeProvider, MiThemeProvider } from './theme';

// 在应用顶层设置主题
function App() {
    return (
        <MiThemeProvider
            value={{
                theme: {
                    cssVar: true,
                    algorithm: [theme.darkAlgorithm], // 使用暗色主题
                },
            }}
        >
            <CompThemeProvider>
                <YourAppContent />
            </CompThemeProvider>
        </MiThemeProvider>
    );
}

在组件中使用主题配置

import { useMiThemeConfig } from './theme';

function ThemedComponent() {
    const { theme } = useMiThemeConfig();

    return (
        <div
            style={{
                background: theme?.token?.colorBgContainer,
                color: theme?.token?.colorText,
            }}
        >
            当前主题: {theme?.algorithm === theme.darkAlgorithm ? '暗色' : '亮色'}
        </div>
    );
}

动态切换主题

function ThemeSwitcher() {
    const { theme, setTheme } = useSomeCustomThemeHook(); // 假设有自定义主题管理

    const toggleTheme = () => {
        setTheme({
            cssVar: true,
            algorithm: [
                theme.algorithm.includes(theme.darkAlgorithm)
                    ? theme.defaultAlgorithm
                    : theme.darkAlgorithm,
            ],
        });
    };

    return (
        <button onClick={toggleTheme}>
            切换{theme.algorithm.includes(theme.darkAlgorithm) ? '亮色' : '暗色'}主题
        </button>
    );
}

默认配置

{
  cssVar: true, // 启用 CSS 变量
  algorithm: [theme.defaultAlgorithm] // 默认使用亮色主题算法
}