素材巴巴 > 程序开发 >

解决antd side侧边栏菜单收缩时二级菜单不跟随

程序开发 2023-09-14 16:33:43

Bug

我又回来了,BUG BUG BUG…
借用下图片,大概就是这种bug,直接看怎么解决吧,简单记录一下,有遇到相同问题的可以试试我这样的方法。

在这里插入图片描述

解决!

import React, { memo, useMemo, useState, useEffect } from "react";
 import { useNavigate, useLocation } from "react-router-dom";
 import { useSelector, shallowEqual } from "react-redux";
 import { Layout, Menu } from "antd";
 import { SildeMenuWrapper } from "./style";
 import { mapIconMenus, deepCopy } from "@/utils/devUtils";
 const { Sider } = Layout;const SideMenu = memo((props: any) => {const location = useLocation();// 路由路径const path = location.pathname;// 默认展开的父节点菜单路径const selectOpen = "/" + (path && path.split("/")[1]);// 用于监听 props.collapsed 改变 在改变前处理 二级菜单选中回闪的bugconst [collapsed, setcollapsed] = useState(props.collapsed);//  动态改变openKeys的值const [menuProps, setmenuProps] = useState({});const { menus } = useSelector((state: any) => ({menus: state.login.menus,}),shallowEqual);// 拿到处理后的菜单数据 先深拷贝再处理 不然会影响到redux中的值const endMenus = useMemo(() => mapIconMenus(deepCopy(menus)), [menus]);const navigate = useNavigate();// 选中菜单的回调const selectMenu = ({ key, domEvent }: any) => {navigate(key);};// 展开菜单的回调const openMenu = (opens: any) => {setmenuProps({ openKeys: opens });};// 用于监听 props.collapsed 改变 收缩前先关闭所有展开项 打开前先展开当前选中项useEffect(() => {if (!props.collapsed) {setcollapsed(props.collapsed);setTimeout(() => {setmenuProps({ openKeys: [selectOpen] });}, 0);} else {setmenuProps({ openKeys: [] });setcollapsed(props.collapsed);}}, [props.collapsed, selectOpen]);return (
全球新闻发布管理系统
); });export default SideMenu;

核心代码都在上面,且有注释!
完整代码看此处项目源码


标签:

素材巴巴 Copyright © 2013-2021 http://www.sucaibaba.com/. Some Rights Reserved. 备案号:备案中。