【发布时间】:2022-10-17 03:11:35
【问题描述】:
我通过使用以下 .tsx 代码 (sandbox demo here) 为每个节点添加上下文菜单来扩展 material ui tree view demo。
import * as React from "react";
import { Typography, Menu, MenuItem } from "@mui/material";
import TreeView from "@mui/lab/TreeView";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import ChevronRightIcon from "@mui/icons-material/ChevronRight";
import TreeItem from "@mui/lab/TreeItem";
interface RenderTree {
id: string;
name: string;
children?: readonly RenderTree[];
}
const data: RenderTree = {
id: "root",
name: "Parent",
children: [
{
id: "1",
name: "Child - 1"
},
{
id: "3",
name: "Child - 3",
children: [
{
id: "4",
name: "Child - 4"
}
]
}
]
};
const NodeWithContextMenu = (props) => {
const [contextMenu, setContextMenu] = React.useState<{
mouseX: number;
mouseY: number;
} | null>(null);
const handleContextMenu = (event: React.MouseEvent) => {
event.preventDefault();
setContextMenu(
contextMenu === null
? {
mouseX: event.clientX + 2,
mouseY: event.clientY - 6
}
: // repeated contextmenu when it is already open closes it with Chrome 84 on Ubuntu
// Other native context menus might behave different.
// With this behavior we prevent contextmenu from the backdrop to re-locale existing context menus.
null
);
};
const handleClose = () => {
setContextMenu(null);
};
return (
<div onContextMenu={handleContextMenu} style={{ cursor: "context-menu" }}>
<Typography>{props.label}</Typography>
<Menu
open={contextMenu !== null}
onClose={handleClose}
anchorReference="anchorPosition"
anchorPosition={
contextMenu !== null
? { top: contextMenu.mouseY, left: contextMenu.mouseX }
: undefined
}
>
<MenuItem onClick={handleClose}>Copy</MenuItem>
<MenuItem onClick={handleClose}>Print</MenuItem>
<MenuItem onClick={handleClose}>Highlight</MenuItem>
<MenuItem onClick={handleClose}>Email</MenuItem>
</Menu>
</div>
);
};
export default function RichObjectTreeView() {
const renderTree = (nodes: RenderTree) => (
<TreeItem
key={nodes.id}
nodeId={nodes.id}
label={<NodeWithContextMenu label={nodes.name} />}
>
{Array.isArray(nodes.children)
? nodes.children.map((node) => renderTree(node))
: null}
</TreeItem>
);
return (
<TreeView
aria-label="rich object"
defaultCollapseIcon={<ExpandMoreIcon />}
defaultExpanded={["root"]}
defaultExpandIcon={<ChevronRightIcon />}
sx={{ height: 110, flexGrow: 1, maxWidth: 400, overflowY: "auto" }}
>
{renderTree(data)}
</TreeView>
);
}
在选择右键单击上下文菜单项时,底层树节点被切换(扩展或收缩)。当单击上下文菜单项或其他任何位置以关闭上下文菜单时,会发生这种情况。
预期行为:上下文菜单的使用应该不是切换底层节点。
这是基本 mui.com 演示的code sandbox 和上面我的code sample。
【问题讨论】:
-
@AllanBowe 请不要将场外位置的代码编辑到此处的帖子中,除非它们是您自己的帖子。您可能在不知不觉中侵犯了版权。请参阅meta.stackexchange.com/q/304331/325771 和meta.stackoverflow.com/q/348698/5211833 以供参考。
-
嗨@Adriaan - 感谢您的关注和节制努力。我正在与 Sabir 合作,我们希望有一个合适的解决方案来支持我们的开源产品 (server.sasjs.io)
标签: javascript reactjs typescript material-ui treeview