【问题标题】:How to add custom colors name on Material UI with TypeScript?如何使用 TypeScript 在 Material UI 上添加自定义颜色名称?
【发布时间】:2021-07-18 14:42:57
【问题描述】:

我正在使用带有 TypeScript 的 Material UI 并希望为我的主题添加自定义颜色。一切正常,除了显示下一条消息的 VSCode linter。

Type '{ tan: string; lightRed: string; red: string; offBlack: string; white: string; }' is not assignable to type 'Partial<CommonColors>'.
  Object literal may only specify known properties, and 'tan' does not exist in type 'Partial<CommonColors>'.

在开发和构建方面工作正常,唯一的抱怨是错误消息。我添加了一个自定义类型来尝试解决,但它不起作用。

const theme = createTheme({
  palette: {
    common: {
      tan,
      lightRed,
      red,
      offBlack,
      white,
    },
  },
});
import {
  PaletteOptions,
  CommonColors,
} from '@material-ui/core/styles/createPalette';

interface CustomColors extends CommonColors {
  tan: string?;
  lightRed: string;
  red: string;
  offBlack: string;
}

declare module '@material-ui/core/styles/createPalette' {
  export interface PaletteOptions {
    common: CustomColors;
  }
}

我添加到 tsconfig.json 文件中。棕褐色、红色和其他值被声明为字符串。关于如何解决这个问题的任何线索?提前致谢。

【问题讨论】:

    标签: reactjs typescript material-ui


    【解决方案1】:

    我不能声称对模块增强有很好的理解,但我已经在我自己的应用程序中完成了它(也适用于调色板中的自定义颜色),并且当我使用与我自己的应用程序相同的方法时,它可以工作适合您的场景。我的理解是您只需要指定扩充 - 您不需要创建扩展现有类型的新类型。在您的情况下,您只想增加 CommonColors

    以下方法似乎有效:

    import "@mui/material/styles/createPalette";
    declare module "@mui/material/styles/createPalette" {
      interface CommonColors {
        tan: string;
        lightRed: string;
        red: string;
        offBlack: string;
      }
    }
    

    在我的示例中,我将此代码放在 createPalette.d.ts 文件中,并且该文件的名称似乎很重要(尽管它在哪个目录中似乎并不重要,只要它在所查看的目录中在由编译器)。将代码直接放入index.tsx 或直接放入执行createTheme 的TypeScript 文件中也可以正常工作。

    相关答案:

    【讨论】:

    • 谢谢先生。你的解决方案就像一个魅力。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-13
    • 2021-12-20
    • 1970-01-01
    • 2021-06-10
    • 2016-02-22
    • 1970-01-01
    相关资源
    最近更新 更多