简体   繁体   English

为 material-ui 主题设置新颜色

[英]Set new color for material-ui theme

I am trying to set a new palette theme for my react app using material-ui's createMuiTheme .我正在尝试使用 material-ui 的createMuiTheme为我的反应应用程序设置一个新的调色板主题。 This is my code for my custom theme:这是我的自定义主题代码:

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;

This is the code where I set the custom theme as the app's theme:这是我将自定义主题设置为应用程序主题的代码:

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;

And this is the code where I try to use color regular in a component:这是我尝试在组件中使用颜色regular的代码:

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

When I use color="primary" or color="secondary" , it works, but color="regular" returns a default light gray color, instead of #73C2FB , that is a light blue.当我使用color="primary"color="secondary"时,它可以工作,但color="regular"返回默认的浅灰色,而不是#73C2FB ,即浅蓝色。

I followed these directions to achieve what I am aiming, but it is not working.我按照这些指示来实现我的目标,但它不起作用。

Custom theme properties can never be applied to any MUI component via the color prop.自定义主题属性永远不能通过color属性应用于任何 MUI 组件。 The reason for this is that MUI takes the the interpolated string value to apply styling via its default props .这样做的原因是 MUI 通过其默认的props采用插入的字符串值来应用样式。 Your example of你的例子

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

would look for a containedRegular property of classes that does not exist.将查找不存在的classescontainedRegular属性。 IIUC MUI should also provide a props validation error . IIUC MUI 还应该提供道具验证错误

Instead, custom theme colors can be applied via the styles or className props.相反,可以通过stylesclassName属性应用自定义主题 colors。

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM