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

问题描述 投票:0回答:3

我尝试将自定义颜色应用于按钮组件,但出现错误。有什么可能的解决方案吗?

我像文档中一样进行了模块模块增强,但问题仍然存在:

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'];
    }
  }

reactjs typescript material-ui
3个回答
11
投票

适用于 MUI 5.11.14 我必须添加

true

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

5
投票

问题在于,在 MUI 中向调色板添加颜色(即使您像此处那样扩展了 createPalette 模块)也不会自动将它们添加到 Button 的可用颜色中。为了允许 Button 的 Color 属性,您还需要扩展一个附加接口:

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,
    }
}

0
投票

我必须调整其他解决方案才能使其发挥作用。

theme.ts

import { PaletteColorOptions, createTheme } from "@mui/material";
import { grey } from "@mui/material/colors";

declare module "@mui/material/styles" {
  interface PaletteOptions {
    myColor: PaletteColorOptions;
  }
}

declare module "@mui/material/Button" { // <-- Added `/Button` here
  interface ButtonPropsColorOverrides {
    myColor: true;
  }
}

const theme = createTheme({
  palette: {
    myColor: {
      main: grey[50]
    }
  }
});

export default theme;

MyComponent.tsx

<Button color="myColor">Click here</Button>
© www.soinside.com 2019 - 2024. All rights reserved.