我正在使用Primreact的树和上下文菜单。执行操作(其中一个菜单项上的单击事件(后,上下文菜单不会隐藏。如果我单击屏幕上的任何位置,上下文菜单将隐藏。这是代码。我遵循primereact提供的相同模式。你能帮我想办法解决这个问题吗?
DemoPrimeTreact.js
import React, {useContext, useEffect, useRef, useState} from 'react';
import 'primereact/resources/themes/saga-blue/theme.css';
import 'primereact/resources/primereact.css';
import 'primeflex/primeflex.css';
import {Tree} from 'primereact/tree';
// other imports
const DemoPrimeReact = () => {
// .... other lines skipped
const [selectedNodeKey, setSelectedNodeKey] = useState(null);
const contextMenu = useRef(null);
return (
<>
<DemoContextMenu
contextMenu={contextMenu} setSelectedNodeKey={setSelectedNodeKey}
//... other props
/>
<Tree
value={[withOrWithoutSearchNodes[0]]}
selectionMode="single" selectionKeys={selectedKey} onSelectionChange={handleSelectionChange}
onSelect={onNodeSelect} onUnselect={onNodeUnselect}
expandedKeys={expandedKeys} onToggle={(event) => setExpandedKeys(event.value)}
contextMenuSelectionKey={selectedNodeKey}
onContextMenuSelectionChange={(event) => setSelectedNodeKey(event.value)}
onContextMenu={(event) => contextMenu.current.show(event.originalEvent)}
dragdropScope="catalog-dnd" onDragDrop={(event) => {
handleCatalogDragAndDrop(event, setLoading, setCanPaste, loadChildrenOnExpand,
setSelectedKey, setExpandedKeys, onNodeSelect, setNodes, expandedKeys);
}}
onExpand={loadChildrenOnExpand} className={classes.primeTree} nodeTemplate={nodeTemplate}
/>
</>
);
}
export default DemoPrimeReact;
DemoContextMenu.js
import React, {useState} from 'react';
import {ContextMenu} from "primereact/contextmenu";
const DemoContextMenu = (props) => {
const { contextMenu, setSelectedNodeKey } = props;
const menu = [
{
label: "Create Library",
template: (item, options) => {
return (
<>
{
nodeInfo && (nodeInfo.node.value.entryType === 'M' ||
nodeInfo.node.value.entryType === 'L') ?
<span
style={{padding: '0 0 0 15px'}}
className={options.className}
>
<Button
onClick={(event) => handleCatalogAction(event, 'createLibrary')}
className={classes.button}
>
<CreateLibraryIcon style={{color: '#68de86'}} />
<span className={classes.item}>Create Library</span>
</Button>
</span> : null
}
</>
);
},
}
];
return (
<>
<ContextMenu
model={menu}
ref={contextMenu}
onHide={() => setSelectedNodeKey(null)}
className={classes.contextMenu}
/>
</>
);
}
export default DemoContextMenu
我认为您可以使用contextMenu.current.state.visible = false;
隐藏带有contextMenu
ref的上下文菜单。
您可以在启动时将这一行放在handleCatalogAction(...)
函数中。在添加上述行之前,可以执行console.log(contextMenu);
以检查current.state.visible
值。