如何使用 mui v5 react typescript 将自定义颜色作为道具?

How to have custom colors as props with mui v5 react typescript?

我希望向 MUI 按钮组件添加一个或多个自定义颜色属性值。我关注了 https://javascript.plainenglish.io/extend-material-ui-theme-in-typescript-a462e207131f,这几乎成功了。我使用了我在 createPalette.d.ts 文件中创建的自定义属性,但是当我尝试在自定义组件中使用它时,它会抛出错误,我无法使用自定义颜色。

遇到错误:

我关注了 Can't customize color palette types on Material UI theme in TypeScript, Material UI 5.0 Typescript React Custom theme, 但运气不好。

但是,它在这里适用于 JavaScript 版本:。但是,对于打字稿版本,我无法遵循它

由于有多个文件,我为相同的文件创建了一个沙箱。 https://codesandbox.io/s/async-rgb-9m6ulo?file=/src/App.tsx

我该如何完成?

在您的 ButtonPropsType.ts

中添加 appcolor 作为可能的类型
type ButtonPropsType = {
  color?:
    | "inherit"
    | "primary"
    | "secondary"
    | "success"
    | "error"
    | "info"
    | "warning"
    | "appcolor"; //<-- Here
  disabled?: boolean;
  variant?: "text" | "outlined" | "contained";
};

或者,如果您想根据需要动态添加选项,mui 有一个接口。

ButtonPropsTypes.ts

import { ButtonProps } from "@mui/material";

type ButtonPropsType = {
  color?: ButtonProps["color"];
  disabled?: boolean;
  variant?: "text" | "outlined" | "contained";
};

export default ButtonPropsType;

createPalette.d.ts

import * as createPalette from "@mui/material/styles/createPalette";

declare module "@mui/material/styles/createPalette" {
  interface PaletteOptions {
    appcolor?: PaletteColorOptions;
  }
  interface Palette {
    appcolor: PaletteColor;
  }
}

declare module "@mui/material" {
  interface ButtonPropsColorOverrides {
    appcolor;
  }
}