如何覆盖 Material-UI MenuItem 选定的背景颜色?

IT技术 reactjs material-ui jss
2021-05-16 13:26:01

目前,我正在努力将MenuItem所选组件的背景颜色设置为不同的颜色。(无需使用 !important 强制它)

组件代码:

<MenuItem
 classes={{
  root: this.props.classes.root,
  selected: this.props.classes.selected
 }}
 value={10}>
  Alfabetical
</MenuItem>

这是CSS:

const homePageStyle = (theme) => ({
  root: {
    width: "300px"
  },
  selected: {
    backgroundColor: "turquoise !important",
    color: "white",
    fontWeight: 600
  }
});

我想达到什么目标?

我想设置 的backgroundColorMenuItem而不必设置 !important 标志。我已经用大量组件完成了这项工作,但目前这似乎行不通。

我正在使用版本“@material-ui/core”:“^1.0.0-rc.0”,

4个回答

我只是在这里做了一个工作示例

为了考虑您选择的类,您必须将组件的selected属性设置MenuItem为 true

<MenuItem
  onClick={this.handleClose}
  selected
  classes={{ selected: classes.selected }}
>

我这样做是为了更改选定的 MenuItem 背景。(由材质 UI 提供的选定props)。

export default createMuiTheme({
  overrides: {
    MuiMenuItem: { // For ListItem, change this to MuiListItem
      root: {
        "&$selected": {       // this is to refer to the prop provided by M-UI
          backgroundColor: "black", // updated backgroundColor
        },
      },
    },
  },
});

这些是可以覆盖的默认值https://material-ui.com/customization/default-theme/#default-theme

参考:https : //material-ui.com/customization/components/#global-theme-override

注意:我使用的是 Material-UI 版本 4.9.11

您可以将样式更新为:

const homePageStyle = (theme) => ({
  root: {
    width: "300px"
  },
  selected: {
    '&.Mui-selected': {
        backgroundColor: "turquoise",
        color: "white",
        fontWeight: 600
    }
  }
});

这是因为 material-ui 如何设计这个组件:.MuiListItem-root.Mui-selected 这两个类的特殊性优先于提供的覆盖。

MUI v5 中,您可以这样做:

<Select
  MenuProps={{
    sx: {
      "&& .Mui-selected": {
        backgroundColor: "pink"
      }
    }
  }}
>

现场演示

代码沙盒演示