首页 > 解决方案 > 为material-ui主题设置新颜色

问题描述

我正在尝试使用 material-ui 为我的反应应用程序设置一个新的调色板主题createMuiTheme。这是我的自定义主题代码:

import {createMuiTheme} from '@material-ui/core/styles';

const customTheme = createMuiTheme({
  palette: {
    primary: {
      main: '#1977d2', //blue
      contrastText: 'white',
    },
    secondary: {
      main: '#FF6600', //orange
      contrastText: 'white',
    },
    regular: {
      main: '#73C2FB' //maya
    }
  }
})

export default customTheme;

这是我将自定义主题设置为应用程序主题的代码:

import './App.css';
import {ThemeProvider} from '@material-ui/core/styles';

import customTheme from './themes/customTheme';
import App from './app/App';

function Main() {
  return (
    <ThemeProvider theme={customTheme}>
      <App />
    </ThemeProvider>
  );
}

export default Main;

这是我尝试regular在组件中使用颜色的代码:

BarButton = ({label, callBack}) => {
    return (
      <Button variant="contained" color="regular" className={this.props.classes.appBarButton} onClick={callBack}>{label}</Button>
    )
  }

当我使用color="primary"orcolor="secondary"时,它可以工作,但color="regular"返回默认的浅灰色,而不是#73C2FB,即浅蓝色。

我按照这些指示来实现我的目标,但它不起作用。

标签: reactjsmaterial-uithemes

解决方案


自定义主题属性永远不能通过colorprop 应用于任何 MUI 组件。这样做的原因是 MUI通过其 default 采用插入的字符串值来应用样式props。你的例子

<Button variant="contained" color="regular">{label}</Button>

会寻找不存在的containedRegular属性。classesIIUC MUI 还应该提供道具验证错误

相反,可以通过stylesor属性应用自定义主题颜色className

const useStyles = makeStyles(theme => ({
  regular: {
    color: theme.palette.regular.main
  }
}))

const classes = useStyles()
const theme = useTheme()

<Button style={{color: theme.palette.regular.main}}>foo</Button>
<Button className={classes.regular}>bar</Button>

推荐阅读