具体实现如下:(antd版本4.19.0)
<Menu mode="inline"
onClick={({ key }) => this.setState({ selectedKeys: [key] })}
onOpenChange={this.onOpenChange.bind(this)} // SubMenu 展开/关闭的回调
openKeys={openKeys} // 当前展开的 SubMenu 菜单项 key 数组
selectedKeys={selectedKeys}
theme="dark"
>
{
menus && menus.map((item: menu) => {
return item.children && item.children.length > 0 ? this.renderSubMenu(item) : this.renderMenuItem(item)
})
}
</Menu>
// 获取点击菜单路径
findMenuKey (menus: menu[], func: any, path: string[] = []) {
if (!menus) return []
for (const data of menus) {
path.push(JSON.stringify(data.key))
if (func(data)) return path
if (data.children) {
const findChildren: any = this.findMenuKey(data.children, func, path)
if (findChildren.length) return findChildren
}
path.pop()
}
return []
}
// 多级菜单时,点击菜单,收起其他菜单
onOpenChange = (openKeys: string[]) => {
const latestOpenKey = openKeys[openKeys.length - 1] // 点击菜单key
const key = this.findMenuKey(menus, (data: any)=>data.key === Number(latestOpenKey))
this.setState({
openKeys: key
})
}