ListItem可以在选中后保持突出显示吗?

时间:2018-01-24 07:56:43

标签: material-ui

我想设置一个主/详细信息视图,左侧是<List>,右侧是<Drawer>

如何突出显示上次选择的<ListItem/>

我正在使用material-ui @ next

1 个答案:

答案 0 :(得分:10)

您应该使用MenuItem代替ListItem。如上所述in the docs

  

MenuItemListItem的包装,带有一些其他样式。

其中一个附加样式是selected选项,您可以使用selected道具设置:

<MenuItem button selected>
  <ListItemIcon>
    <FolderIcon />
  </ListItemIcon>
  <ListItemText primary="Archives" />
</MenuItem>

以下是使用state跟踪和更新最近点击的项目的概念证明:

import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from 'material-ui/styles';
import List, { ListItemIcon, ListItemText } from 'material-ui/List';
import { MenuItem } from 'material-ui/Menu';
import InboxIcon from 'material-ui-icons/Inbox';
import DraftsIcon from 'material-ui-icons/Drafts';
import FolderIcon from 'material-ui-icons/Folder';

const styles = theme => ({
  root: {
    width: '100%',
    maxWidth: 360,
    backgroundColor: theme.palette.background.paper,
  },
});

class SimpleList extends React.Component {
  constructor(props) {
    super(props);

    this.state = { selected: null };
  }

  updateSelected(selectedIndex) {
    this.setState({ selected: selectedIndex });
  }

  render() {
    const { classes } = this.props;
    const { selected } = this.state;

    return (
      <div className={classes.root}>
        <List>
          <MenuItem button onClick={() => this.updateSelected(0)} selected={selected === 0}>
            <ListItemIcon>
              <InboxIcon />
            </ListItemIcon>
            <ListItemText primary="Inbox" />
          </MenuItem>
          <MenuItem button onClick={() => this.updateSelected(1)} selected={selected === 1}>
            <ListItemIcon>
              <DraftsIcon />
            </ListItemIcon>
            <ListItemText primary="Drafts" />
          </MenuItem>
          <MenuItem button onClick={() => this.updateSelected(2)} selected={selected === 2}>
            <ListItemIcon>
              <FolderIcon />
            </ListItemIcon>
            <ListItemText primary="Archives" />
          </MenuItem>
        </List>
      </div>
    );
  }
}

SimpleList.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(SimpleList);