[英]Typescript/React/MUI use custom color on Button component
我试图将自定义颜色应用于 Button 组件,但出现错误。 有什么可能的解决方案?
我像在文档中一样进行了模块模块扩充,但问题仍然存在:
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<...>'
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'];
}
}
问题在于,将 colors 添加到 MUI 中的调色板(即使您像此处那样扩充 createPalette 模块)不会自动将它们添加到按钮的可用 colors 中。 为了允许 Button 的 Color 属性,还需要扩展一个额外的接口:
declare module '@mui/material' {
interface ButtonsPropsColorOverrides {
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,
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.