reactjs Typescript/React/MUI在Button组件上使用自定义颜色

xdnvmnnf  于 2023-03-29  发布在  React
关注(0)|答案(2)|浏览(125)

我试图将自定义颜色应用到按钮组件,但我得到错误。什么是可能的解决方案?
我做了像文档中的模块模块增强,但问题仍然存在:
https://mui.com/material-ui/customization/palette/#adding-new-colors
留言:Button.d.ts(34, 5): The expected type comes from property 'color' which is declared here on type 'IntrinsicAttributes & { component: ElementType<any>; } & { children?: ReactNode; classes?: Partial<ButtonClasses> | undefined; ... 10 more ...; variant?: "text" | ... 2 more ... | undefined; } & Omit<...> & CommonProps & Omit<...>'

const theme = createTheme({
  palette: {
    primary: {
      main: '#ff0000',
    },
    play: {
      main: '#ffffff',
      contrastText: 'black'
    },
    moreInfo: {
      main: '#6c6c6e',
      contrastText: 'white'
    },
    tonalOffset: 0.2,
  },
  breakpoints: {
    values: {
      xs: 0,
      sm: 600,
      md: 900,
      lg: 1200,
      xl: 1536,
    },
  },
});
import { createTheme } from '@mui/material/styles'

declare module '@mui/material/styles' {
    interface Palette {
        play?: Palette['primary'];
        moreInfo?: Palette['primary'];
    }
    interface PaletteOptions {
        play?: PaletteOptions['primary'];
        moreInfo?: PaletteOptions['primary'];
    }
  }

8oomwypt

8oomwypt1#

问题是,在MUI中向调色板添加颜色(即使您在这里扩展了createPalette模块)也不会自动将它们添加到Button的可用颜色中。为了允许Button的Color prop,您还需要扩展一个额外的接口:

declare module '@mui/material' {
    interface ButtonPropsColorOverrides {
        play,
        moreInfo,
    }
}

您需要在每个组件的基础上执行此操作。我还以稍微不同的方式扩展了createPalette,但您的方法可能也是正确的:

import "@mui/material/styles/createPalette";
declare module '@mui/material/styles/createPalette' {
    interface PaletteOptions {
        play?: PaletteColorOptions,
        moreInfo?: PaletteColorOptions,
    }

    interface Palette {
        play: PaletteColor,
        moreInfo: PaletteColor,
    }
}
bmp9r5qi

bmp9r5qi2#

对于MUI 5.11.14,我必须添加true

declare module "@mui/material" {
  interface ButtonPropsColorOverrides {
    myCoolColour: true;
  }
}

相关问题