React中MUI Button组件颜色修改失效问题求助
MUI的Button组件的color属性仅支持官方预设的枚举值(primary、secondary、error、info、success、warning),直接传入"yellow"不会触发颜色变化,以下是几种可行的解决方式:
方法一:直接用sx样式覆盖
通过sx属性直接设置按钮的背景色、文字色及hover状态:
<Button onClick={goToLogin} variant="contained" sx={{ mt: 2, backgroundColor: 'yellow', color: 'black', // 调整文字颜色提升可读性 '&:hover': { backgroundColor: '#e6e600', // 自定义hover时的黄色 } }} > ÜCRETSİZ KAYIT OLUN </Button>
方法二:扩展MUI主题自定义颜色
先在主题中添加自定义的黄色调色板,再通过color属性调用:
- 配置主题:
import { createTheme, ThemeProvider } from '@mui/material/styles'; const customTheme = createTheme({ palette: { yellow: { main: '#ffff00', // 主色 contrastText: '#000', // 文字对比色 }, }, });
- 在主题包裹下使用按钮:
<ThemeProvider theme={customTheme}> <Button onClick={goToLogin} variant="contained" color="yellow" sx={{ mt: 2 }} > ÜCRETSİZ KAYIT OLUN </Button> </ThemeProvider>
方法三:使用MUI内置黄色变量
利用MUI调色板中预设的黄色色值,适配主题风格:
<Button onClick={goToLogin} variant="contained" sx={{ mt: 2, backgroundColor: (theme) => theme.palette.yellow[500], color: (theme) => theme.palette.getContrastText(theme.palette.yellow[500]), '&:hover': { backgroundColor: (theme) => theme.palette.yellow[700], } }} > ÜCRETSİZ KAYIT OLUN </Button>
内容的提问来源于stack exchange,提问作者Halilibrahim Demir
相关产品推荐
相关产品推荐

