如何将折叠/展开图标更改为材质 TreeView 的右侧?

IT技术 reactjs material-ui
2021-05-18 20:49:46

我正在尝试使用 Reactjs 中的材料来实现一棵树。但是,根据我的设计,折叠和展开的按钮应该在右侧。

另外,在添加这样的图标时出现错误TreeItem

<TreeItem nodeId="1" label="RSMSSB" icon={FolderIcon}>

全码:

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import TreeView from "@material-ui/lab/TreeView";
import ExpandMoreIcon from "@material-ui/icons/ExpandMore";
import ChevronRightIcon from "@material-ui/icons/ChevronRight";
import TreeItem from "@material-ui/lab/TreeItem";
import FolderIcon from '@material-ui/icons/Folder';
const useStyles = makeStyles({
  root: {
    height: 216,
    flexGrow: 1,
    maxWidth: 400
  }
});

export default function ControlledTreeView() {
  const classes = useStyles();
  const [expanded, setExpanded] = React.useState([]);

  const handleChange = (event, nodes) => {
    setExpanded(nodes);
  };

  return (
    <TreeView
      className={classes.root}
      defaultCollapseIcon={<ExpandMoreIcon />}
      defaultExpandIcon={<ChevronRightIcon />}
      expanded={expanded}
      onNodeToggle={handleChange}
    >
      <TreeItem nodeId="1" label="RSMSSB" icon={FolderIcon}>
        <TreeItem nodeId="2" label="Science"></TreeItem>
        <TreeItem nodeId="3" label="Mathematics">
          <TreeItem nodeId="4" label="Polynomials"></TreeItem>
          <TreeItem nodeId="7" label="Inequalities"></TreeItem>
        </TreeItem>
        <TreeItem nodeId="8" label="English"></TreeItem>
      </TreeItem>
    </TreeView>
  );
}

模拟设计:

在此处输入图片说明

谢谢。

编辑:
工作示例:https : //codesandbox.io/s/purple-night-mgzwh

1个回答

基于自定义树视图示例,您可以创建一个自定义组件,该组件将文本图标传递给 的标签属性,TreeItem并将右侧的展开/折叠图标添加flex-direction: row-reverse;到 的内容TreeItem

const useTreeItemStyles = makeStyles(theme => ({
  content: {
    flexDirection: 'row-reverse'
  },
  labelRoot: {
    display: 'flex',
    alignItems: 'center',
    padding: theme.spacing(0.5, 0),
  },
  labelIcon: {
    marginRight: theme.spacing(1),
  },
  labelText: {
    fontWeight: 'inherit',
    flexGrow: 1,
  },
}));

function StyledTreeItem(props) {
  const classes = useTreeItemStyles();
  const { labelText, labelIcon: LabelIcon, ...other } = props;

  return (
    <TreeItem
      label={
        <div className={classes.labelRoot}>
          <LabelIcon color="inherit" className={classes.labelIcon} />
          <Typography variant="body2" className={classes.labelText}>
            {labelText}
          </Typography>
        </div>
      }
      classes={{
        content: classes.content
      }}
      {...other}
    />
  );
}

...

<TreeView
      className={classes.root}
      defaultCollapseIcon={<ExpandMoreIcon />}
      defaultExpandIcon={<ChevronRightIcon />}
      expanded={expanded}
      onNodeToggle={handleChange}
    >
      <StyledTreeItem nodeId="1" labelText="RSMSSB" labelIcon={FolderIcon} />

...

工作示例:

编辑 green-surf-dcoqr