AntD Menu.Item设置Key失败,拖拽菜单项出现选中异常问题
问题修复:Ant Design菜单拖拽后选中异常+Key未定义警告
问题根源
- DOM结构破坏:用
div包裹Menu.Item后,Ant Design的Menu组件无法识别正确的子节点结构(Menu要求直接子节点必须是Menu.Item/Menu.SubMenu),导致菜单选中状态混乱、点击事件无法传递正确的key。 - Key异常:要么
child.key本身为undefined,要么重复给div和内部Menu.Item设置了相同key,触发控制台「Duplicated key 'undefined'」警告。
修复步骤&代码调整
1. 移除包裹Menu.Item的div,改用React.Fragment
把拖拽所需的ref、listeners、attributes直接绑定到Menu.Item上,既保留拖拽功能,又不破坏Menu的结构:
// 整合拖拽逻辑和菜单项,减少层级 function DraggableSidebarItem({ item, ...rest }: TChildProp) { const { attributes, listeners, setNodeRef } = useDraggable({ // 优先用item.key作为拖拽id,关联更紧密 id: item.key || uuidv4(), data: { item, fromSidebar: true, }, }); return ( <React.Fragment key={item.key}> <Menu.Item ref={setNodeRef} {...listeners} {...attributes} onClick={(e) => console.log("点击的key:", e.key)} style={{ margin: "0px" }} key={item.key} icon={item.icon} {...rest} > {item.label} </Menu.Item> </React.Fragment> ); }
如果要保留SidebarItem组件,调整它支持接收拖拽属性:
function SidebarItem({ item, overlay, dragProps }: TChildProp & { dragProps?: any }) { return ( <Menu.Item onClick={(e) => console.log("点击的key:", e.key)} style={{ margin: "0px" }} key={item.key} icon={item.icon} {...dragProps} {...overlay} > {item.label} </Menu.Item> ); } function DraggableSidebarItem({ item, ...rest }: TChildProp) { const { attributes, listeners, setNodeRef } = useDraggable({ id: item.key || uuidv4(), data: { item, fromSidebar: true, }, }); const dragProps = { ref: setNodeRef, ...listeners, ...attributes }; return <SidebarItem key={item.key} item={item} dragProps={dragProps} {...rest} />; }
2. 确保fields数据中child的key有效且唯一
检查你的fields对象,保证每个子项的key存在且不重复,示例结构如下:
const fields = { Form_Organiser: { key: "Form_Organiser", label: "表单组织器", icon: <FolderOutlined />, children: [ { key: "section", label: "分区", icon: <PartitionOutlined /> }, { key: "container", label: "容器", icon: <ContainerOutlined /> }, ] }, // ...其他父菜单配置 };
修复效果说明
- 去掉外层div后,Menu能正确识别每个菜单项,点击单个项只会选中对应项,点击事件能拿到正确的
key。 - 确保
item.key有效后,控制台的「Duplicated key」警告会消失,拖拽功能也能正常关联对应的菜单项数据。
内容的提问来源于stack exchange,提问作者KwanYee Tan
相关产品推荐
相关产品推荐

