我正在尝试使用 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'.
最佳答案
PaletteColorOptions
是 type
– 不是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/