将 type: 'dark' 应用到 MUI 调色板会破坏我的网站,除非它直接在 createMuiTheme() 函数中定义

Applying type: 'dark' to a MUI palette breaks my site unless it is defined directly in the createMuiTheme() function

在直接 createMuiTheme() 功能之外的任何地方声明 type: 'dark' 时,我无法使用 MUI 为我的站点定义 'dark' 主题。

例如以下作品:

const siteTheme = createMuiTheme({
  palette: {
    primary: {
      light: '#484848',
      main: '#212121',
      dark: '#000000',
      contrastText: '#fff',
    },
    secondary: {
      light: '#b0ff57',
      main: '#76ff03',
      dark: '#32cb00',
      contrastText: '#000',
    },
    type: 'dark'
  },
})

但以下中断:

const theme = {
  palette: {
    primary: {
      light: '#484848',
      main: '#212121',
      dark: '#000000',
      contrastText: '#fff',
    },
    secondary: {
      light: '#b0ff57',
      main: '#76ff03',
      dark: '#32cb00',
      contrastText: '#000',
    },
    type: 'dark'
  },
}

const siteTheme = createMuiTheme(theme)

它给出的错误是

54 | const siteTheme = createMuiTheme(theme)

Argument of type '{ palette: { primary: { light: string; main: string; dark: string; contrastText: string; }; secondary: { light: string; main: string; dark: string; contrastText: string; }; type: string; }; }' is not assignable to parameter of type 'ThemeOptions'. Types of property 'palette' are incompatible. Type '{ primary: { light: string; main: string; dark: string; contrastText: string; }; secondary: { light: string; main: string; dark: string; contrastText: string; }; type: string; }' is not assignable to type 'PaletteOptions'. Types of property 'type' are incompatible. Type 'string' is not assignable to type '"dark" | "light" | undefined'.ts(2345)

我正在使用 .tsx 文件。

为什么我不能在直接 createMuiTheme() 函数之外定义 type = 'dark'

因为您使用的是 TypeScript,所以您需要确保将其转换为正确的类型:

import { PaletteType } from '@material-ui/core';

const theme = {
  palette: {
    type: 'dark' as PaletteType,
  }
}

以来,命名似乎发生了变化,因此我添加了一个更新的答案,以防将来有人像我一样偶然发现这个问题。

我在 @material-ui/core/index.d.ts:50 找到了以下行,因此我假设作者已决定将调色板“type”重命名为“mode”:

export type PaletteMode = 'light' | 'dark';

这是一个 App.tsx 的最小工作示例(假设默认值 index.tsxcreate-react-app 或类似的生成):

import React from "react";
import { createMuiTheme, PaletteMode, ThemeProvider } from "@material-ui/core";

const theme = createMuiTheme({
  palette: {
    mode: "dark" as PaletteMode
  }
});

export default function App() {
  return (
    <ThemeProvider theme={theme}>
      <CssBaseline />
      <div className="App" />
    </ThemeProvider>
  );
}

作为旁注,也应该可以使用 useMediaQuery("(prefers-color-scheme: dark)") 来确定用户是喜欢深色主题还是浅色主题,并像这样自动设置合适的主题:

mode: (useMediaQuery("(prefers-color-scheme: dark)") ? "dark" : "light") as PaletteMode

另一个小 addition/note:不要忘记在 <ThemeProvider> 的顶部添加 <CssBaseline />,通常在根 element/component.

之上