reactjs - Material UI 使用 typescript 在调色板的主要对象上定义一个新属性

标签 reactjs typescript material-ui

我正在尝试使用 MUI v5 自定义主题以使其在我的项目中工作,到目前为止我可以根据我的需要自定义我的主题,但现在的问题是我需要添加一个新属性我的主要对象在调色板内定义,默认情况下调色板中的每个对象应该有 4 个主要属性 -

light?: string;
  main: string;
  dark?: string;
  contrastText?: string;

但是如果我想向其中添加一个新属性(例如“magic”)怎么办?

主题.ts

import { createTheme, Theme } from "@mui/material/styles";
import { brown, red } from "@mui/material/colors";

declare module "@mui/material/styles/createPalette" {
  interface Palette {
    brown: PaletteColor;
  }

  interface PaletteOptions {
    brown: PaletteColorOptions;
  }
}

declare module "@mui/material/styles" {
  // fix the type error when referencing the Theme object in your styled component
  interface Theme {
    myField?: {
      myNestedField?: string;
    };
  }
  // fix the type error when calling `createTheme()` with a custom theme option
  interface ThemeOptions {
    myField?: {
      myNestedField: {
        margin?: string;
      };
    };
  }
}

export const theme = createTheme({
  palette: {
    primary: {
      main: "#ffffff",
      magic:'#000000 ///throws error - 
    },
    brown: {
      main: brown[300],
    },
  },
  myField: {
    myNestedField: { margin: "10px 5px" },
  },
});

所以当我在 parimary 中定义“magic”时,我收到错误

Type '{ main: string; magic: string; }' is not assignable to type 'PaletteColorOptions | undefined'. Object literal may only specify known properties, and 'magic' does not exist in type 'PaletteColorOptions'.

最佳答案

PaletteColorOptionstype – 不是interface所以我们不能使用module augmentation在上面。但幸运的是它是由两个接口(interface)组成的:type PaletteColorOptions = SimplePaletteColorOptions | ColorPartial 。所以我们可以增强接口(interface)SimplePaletteColorOptions像这样:

declare module '@mui/material/styles/createPalette' {
  interface SimplePaletteColorOptions {
    magic: string
  }
}

关于reactjs - Material UI 使用 typescript 在调色板的主要对象上定义一个新属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70624056/

相关文章:

css - Material UI表格中排序图标的样式怎么改?

reactjs - Material-UI 主题覆盖 : How To Override Children Styles Globally?

reactjs - ClickAwayListener 组件不适用于 DragDropContext

reactjs - 将视频播放器添加到带有控件的 GLB 模型

reactjs - createAsyncThunk 并使用 redux-toolkit 编写 reducer 登录

typescript - 使用 Typescript 创建自定义 Jasmine 匹配器

typescript - 如何在 Angular 8 中使用延迟加载模块的通用指令

javascript - 为什么我的 CSS 背景图像无法在 Electron 中加载?

javascript - 如何在 React 中处理对 setState 的异步调用?

javascript - Angular2 中的表单异步验证