How to programmatically expand or collapse Tree Item in Material Ui?

做~自己de王妃 提交于 2021-01-27 04:28:09

问题


Is there any way to programmatically expand and collapse tree items in material ui? I can do that by clicking on the item, but there are other times when I would like to collapse and expand the tree items based on an action in the tree view. is it possible?


回答1:


You can achieve that using TreeView expanded prop.
The code below expands the TreeItem with id "1" on mount.

import React, {useEffect, useState} from 'react';
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';

export default function FileSystemNavigator() {
  const [expanded, setExpanded] = useState([]);

  useEffect(() => {
    setExpanded(["1"])
  },[])

  return (
    <TreeView
      defaultCollapseIcon={<ExpandMoreIcon />}
      defaultExpandIcon={<ChevronRightIcon />}
      expanded={expanded}
    >
      <TreeItem nodeId="1" label="Applications"    
>
        <TreeItem nodeId="2" label="Calendar" />
        <TreeItem nodeId="3" label="Chrome" />
        <TreeItem nodeId="4" label="Webstorm" />
      </TreeItem>
      <TreeItem nodeId="5" label="Documents"
>
        <TreeItem nodeId="6" label="Material-UI">
          <TreeItem nodeId="7" label="src">
            <TreeItem nodeId="8" label="index.js" />
            <TreeItem nodeId="9" label="tree-view.js" />
          </TreeItem>
        </TreeItem>
      </TreeItem>
    </TreeView>
  );
}

Code Sandbox




回答2:


This answer is for Riham Nour Question in the comment section of this answer (won't be able to reply in comments due to less reputation).

what if I only want the selected parent TreeItem to be selected while collapsing the others? like when I select node 1, then node 6 collapses ?

Just add the nodeId of the selected nodes then you can easily be able to get the desired outcome. You can go through the code Code SandBox.

PS: I hope I understood the question correctly and Sorry I added this in the answer section. Please let me know if there is any better way to communicate the answer to Riham.



来源:https://stackoverflow.com/questions/57742324/how-to-programmatically-expand-or-collapse-tree-item-in-material-ui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!