You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为React Syncfusion Tree Grid自定义上下文菜单绑定菜单项点击事件?

实现方法

你可以通过为ContextMenuComponent绑定select事件,结合菜单项的唯一标识来实现自定义触发逻辑,具体修改如下:

步骤1:给菜单项添加唯一标识

在定义menuItems时,为每个需要触发事件的菜单项添加唯一id字段,用于区分点击的是哪一项,同时修正原代码中多余的闭合括号语法问题:

const [menuItems, setMenuItems] = useState([
  {
    text: "Change Color",
    iconCss: "e-cm-icons e-cut",
    items: [
      {
        id: "color-blue", // 新增唯一标识
        text: "Blue",
        iconCss: "e-cm-icons e-pastetext",
      }, 
      {
        id: "color-black", // 新增唯一标识
        text: "Black",
        iconCss: "e-cm-icons e-pastespecial",
      },
    ]
  }
]);

步骤2:给ContextMenuComponent绑定select事件

为ContextMenuComponent添加onSelect属性,绑定自定义的菜单点击处理函数:

<ContextMenuComponent 
  target="#contextmenutarget"
  items={menuItems}
  onSelect={handleMenuSelect} // 新增点击事件绑定
/>

同时记得修正TreeGridComponent原代码中childMapping="subtasks""多写的多余双引号,避免语法报错。

步骤3:实现自定义处理函数

在函数内判断点击的菜单项,结合TreeGrid选中的行实现样式修改逻辑:

const handleMenuSelect = (args) => {
  // 获取点击的菜单项ID
  const selectedMenuId = args.item.id;
  // 获取TreeGrid实例
  const treeGrid = document.getElementById('contextmenutarget').ej2_instances[0];
  // 获取当前选中的行DOM元素
  const selectedRows = treeGrid.getSelectedRows();
  if (!selectedRows.length) return;

  // 根据菜单项执行对应逻辑
  switch(selectedMenuId) {
    case 'color-blue':
      // 给选中行添加自定义样式类
      selectedRows.forEach(row => {
        row.classList.remove('custom-black');
        row.classList.add('custom-blue');
      });
      // 如需操作行数据可调用 treeGrid.getSelectedRecords() 获取选中行数据
      break;
    case 'color-black':
      selectedRows.forEach(row => {
        row.classList.remove('custom-blue');
        row.classList.add('custom-black');
      });
      break;
    default:
      break;
  }
}

步骤4:添加自定义样式

在全局或组件对应的CSS文件中定义样式类:

.custom-blue {
  background-color: #e3f2fd !important;
  color: #1976d2 !important;
}

.custom-black {
  background-color: #f5f5f5 !important;
  color: #212121 !important;
}

内容的提问来源于stack exchange,提问作者Sourabh Date

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 08:36:03