TreeItem
的展开/折叠功能(如果您正在运行的话)。据推测,您应该能够轻松地将 TreeView
更改为在受控模式下运行,方法是保持展开的项目列表处于状态,将该列表传递给 TreeView
的 expanded
属性,然后强制它通过不为您不想折叠的 TreeItem
提供单击处理程序来保持顶级项目的展开。例如:
...
// Setting the top-level node's nodeId to "expanded", by default
const [expanded, setExpanded] = React.useState(["1"]);
// Handle the expand logic however you choose (this is just an example)
const createHandler = (id) => () => {
if (!expanded.includes(id)) {
setExpanded([...expanded, id]);
} else {
setExpanded(
expanded.filter((i) => {
return i !== id && !i.startsWith(`${id}.`);
})
);
}
};
...
return (
<TreeView
className={classes.root}
defaultCollapseIcon={<ExpandMoreIcon />}
defaultExpandIcon={<ChevronRightIcon />}
expanded={expanded}
>
{/* Don't provide a click handler to this node so it won't collapse */}
{/* Note: I'm passing an empty fragment to the `collapseIcon` prop so no collapse icon is displayed */}
<TreeItem nodeId="1" label="All Items" collapseIcon={<></>}>
{/* Provide a click handler for all collapsible children */}
<TreeItem
nodeId="2"
label="Second Level Item"
onClick={createHandler("2")}
/>
...
</TreeView>
);
...
上面的示例还包括一种通过将空的 React Fragment 传递给
collapseIcon
属性来删除折叠图标的方法 - 但如果您愿意,您也可以使用一些巧妙的 CSS 来实现此目的。
工作CodeSandbox:https://codesandbox.io/s/material-demo-forked-4nmsp6?file=/demo.tsx:1514-1699