【问题标题】:Set new color for material-ui theme为material-ui主题设置新颜色
【发布时间】:2021-04-08 13:27:41
【问题描述】:

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

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"color="secondary" 时,它可以工作,但color="regular" 返回默认的浅灰色,而不是#73C2FB,即浅蓝色。

我关注these directions 以实现我的目标,但它不起作用。

【问题讨论】:

  • Button 仅限 supports primarysecondary 主题颜色。各种 MUI 组件支持不同的 palette 属性作为 color 属性的字符串值,但从不支持自定义属性。您需要通过styleclassName 属性将其应用为theme.palette.regular.main
  • @hotpink 谢谢伙计,它成功了。您应该将其发布为答案,以便其他有同样疑问的人得到解决。你也收集了一些积分。

标签: reactjs material-ui themes


【解决方案1】:

自定义主题属性永远不能通过 color 属性应用于任何 MUI 组件。原因是 MUI 采用 interpolated string value 通过其默认的 props 应用样式。你的例子

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

将查找不存在的classescontainedRegular 属性。 IIUC MUI 还应提供props validation error

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

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-03
    • 2019-12-29
    • 2020-08-06
    • 2020-01-24
    • 1970-01-01
    • 2018-10-23
    相关资源
    最近更新 更多