如何更改所选ItemList Material-Ui的背景颜色

hig*_*nce 3 javascript reactjs material-ui

我使用Material-UI创建了一个可选组件

let SelectableInfiniteList = makeSelectable(Infinite);
Run Code Online (Sandbox Code Playgroud)

并将ListItem放入其中,现在我想更改所选项目的默认灰色,但我不知道如何给它一个className

<ListItem className="list-item" primaryText={i}/>
Run Code Online (Sandbox Code Playgroud)

并使用list-item:焦点选择器我可以改变背景颜色,只要它被聚焦(但是如果我点击应用程序中的其他地方)焦点会丢失并且灰色会显示在(仍然)所选项目上,

有没有办法改变选定的项目背景颜色?

thi*_*ign 7

我不得不使用全局主题覆盖:https : //material-ui.com/customization/components/#global-theme-override

const muiTheme = createMuiTheme({
  overrides: {
    MuiListItem: {
      root: {
        "&$selected": {
          backgroundColor: "red",
          "&:hover": {
            backgroundColor: "orange",
          },
        },
      },
      button: {
        "&:hover": {
          backgroundColor: "yellow",
        },
      },
    },
  },
});
Run Code Online (Sandbox Code Playgroud)


hig*_*nce 6

在您的高阶组件中添加新属性selectedItemStyle!

<ComposedComponent selectedItemStyle={selectedItemStyle} value={this.state.selectedIndex} onChange={this.handleRequestChange} containerHeight={this.props.containerHeight} elementHeight={40}>
   {this.props.children}
</ComposedComponent>
Run Code Online (Sandbox Code Playgroud)

其中selectedItemStyle是

const slectedItemStyle = {
 backgroundColor: 'red'
}
Run Code Online (Sandbox Code Playgroud)


Amr*_* LS 6

通过selected像这样传递样式来更改默认选择的灰色。

<ListItem
        button
        selected={true}
        classes={{ selected: classes.active }}>
  <ListItemText primary={item.name} />
</ListItem>
Run Code Online (Sandbox Code Playgroud)

样式对象应该是这样的。

active: {
  backgroundColor: "red"
}
Run Code Online (Sandbox Code Playgroud)

  • 对我来说,这被“.MuiListItem-root.Mui-selected”覆盖。 (7认同)

Sea*_*son 6

如果您对不覆盖全局样式的方法感兴趣,

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

const useStyles = makeStyles({
  root: {
    '&$selected': {
      backgroundColor: 'red',
      '&:hover': {
        backgroundColor: 'yellow',
      }
    },
  },
  selected: {},
});

const CustomSelectedListItem = (
  <ListItem
    button
    classes={{ root: classes.root, selected: classes.selected }}
    selected
  >
    <ListItemText primary="List Item" />
  </ListItem>
);
Run Code Online (Sandbox Code Playgroud)

代码沙盒。Material-UI文档


小智 5

const theme = createTheme({
  components: {
    MuiListItem: {
      styleOverrides: {
        root: {
          backgroundColor: 'blue',

          '&.Mui-selected': {
            backgroundColor: 'red',
          },
        },
      },
    },
  },
});
Run Code Online (Sandbox Code Playgroud)