【问题标题】:How to add css variable to createMuiTheme如何将css变量添加到createMuiTheme
【发布时间】:2020-07-19 18:22:05
【问题描述】:

我在我的组件中使用了 MuiThemeProvider,我想为 MUI 中的 MenuItem 设置样式。我在这里所做的是用createMuiTheme 像这样创建一个变量

const themes = createMuiTheme({
   overrides: {
      MuiListItem: {
         root: {
           "&$selected": {
              background: '#459FB6',
              color: '#fff',
            }
         }
      }
   }
});

我像这样将它传递给我的 ThemeProvider

     <MuiThemeProvider theme={themes}>
        <MenuItem>
           Menu Item
        </MenuItem>
     </MuiThemeProvider>

我还有一个带有调色板的对象,我想在我的themes 中使用它们。我的问题是如何实现这样的目标

const themes = createMuiTheme({
   overrides: {
      MuiListItem: {
         root: {
           "&$selected": {
              background: colors.blue, // here i want to use my custom variable
              color: colors.white, // here i want to use my custom variable
            }
         }
      }
    }
});

提前致谢!

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    如果其他人遇到同样的问题,我创建了这个答案。我通过使用makeStyles 而不是createMuiTheme 和ThemeProvider 实现了这一点。代码示例在下面

    const useStyle = makeStyles({
      root: {
         "&:hover": {
            backgroundColor: `${theme.colors.highlight}`,
            color: `${theme.colors.white}`,
         }
      },
      selected: {
         "&$selected": {
            backgroundColor: `${theme.colors.textLink}`,
            color: `${theme.colors.white}`,
         },
         "&$selected:hover": {
            backgroundColor: `${theme.colors.highlight}`,
            color: `${theme.colors.white}`,
         },
      },
    });
    
    const classes = useStyle();
    

    然后我像这样将classes 传递给我的 MenuItem 组件

        <MenuItem classes={{ root: classes.root, selected: classes.selected}}>
           Menu Item
        </MenuItem>
    

    瞧!

    【讨论】:

      猜你喜欢
      • 2021-01-03
      • 1970-01-01
      • 2020-10-15
      • 2021-09-08
      • 2023-03-14
      • 1970-01-01
      • 2020-11-22
      • 2019-09-13
      • 1970-01-01
      相关资源
      最近更新 更多