antd 5X中 tree属性结构,自定义菜单,右键菜单实现方式
第一种方式
- 使用自定义渲染节点 titleRender
<TreetitleRender={titleRender}autoExpandParent={autoExpandParent}fieldNames={fieldNames}treeData={treeData}></Tree>
重要代码
titleRender实现方式
const menu = (<Menuitems={[{key: 'add',label: <span>新增</span>,},{key: 'delete',label: <span>删除</span>,},{key: 'update',label: <span>编辑</span>,},]}/>);// 自定义节点渲染const titleRender = (nodeData: any) => {return (<Dropdown overlay={menu} trigger={['contextMenu']}><div>{nodeData.name}SB</div></Dropdown>);};相当于每一个节点就是<Dropdown overlay={menu} trigger={['contextMenu']}><div>{nodeData.name}SB</div></Dropdown>这个组件
另外一种方式
index.tsxconst treeRightMenu = {menuId: '1',items: [{ key: 'add', name: '添加同级节点', handler: (props: any) => { handleItemClick('add', props)}},{ key: 'edit', name: '修改此节点', handler: (props: any) => { handleItemClick('edit', props)}},{ key: 'addSub', name: '添加子节点', handler: (props: any) => { handleItemClick('addSub', props)}},{ key: 'del', name: '添加此节点', handler: (props: any) => { handleItemClick('del', props)}},],};<TreeRightdataSource={treeData}contextMenu={treeRightMenu}onSelect={handleSelect}/>treeright.tsx
// components/TreeRight.tsximport { Tree } from 'antd';
import { Menu, Item, useContextMenu } from 'react-contexify';
import 'react-contexify/dist/ReactContexify.min.css';type TreeRightProps = {dataSource: any[];contextMenu: any;onSelect: (selectedKeys: any, info: any ) => void;
};// const MENU_ID = '1';
const TreeRight: React.FC<TreeRightProps> = (props) => {const { dataSource, contextMenu, onSelect} = props;// 右键菜单const ContextMenu = () => (<Menu id={contextMenu.menuId}>{contextMenu.items.map((item: any) => (// 这里需要加key,不然要报错<Item key={item.key} onClick={item.handler}>{item.name}</Item>))}</Menu>);const { show } = useContextMenu({id: contextMenu.menuId,});// 右键显示菜单const handleContextMenu = (event: any, node: any) => {event.preventDefault();show(event,{props: node,});}return (<div><TreeautoExpandParentdefaultExpandAlldefaultExpandParenttreeData={dataSource}onSelect={onSelect}// 右键事件onRightClick={({event, node}: any) => {handleContextMenu(event, node)}}/><ContextMenu /></div>);
};export default TreeRight;
值得一提React Contexify 是一个用于在 React 应用中创建上下文菜单(右键菜单)的开源库。它允许开发者轻松地在任何 React 组件中添加自定义的上下文菜单,提供了丰富的 API 和事件处理机制,使得上下文菜单的创建和管理变得简单高效。
npm install react-contexify 你需要通过 npm 或 yarn 安装
简单使用实例
import React from 'react';
import { Menu, Item, useContextMenu } from 'react-contexify';
import 'react-contexify/dist/ReactContexify.css';const MENU_ID = 'menu_id';function App() {const { show } = useContextMenu({id: MENU_ID,});const handleItemClick = ({ event, props, trigger }) => {console.log('Item clicked', props, trigger);};return (<div><div onContextMenu={show}>Right click here</div><Menu id={MENU_ID}><Item onClick={handleItemClick}>Item 1</Item><Item onClick={handleItemClick}>Item 2</Item></Menu></div>);
}export default App;