记录一下ant.design Menu收起菜单 弹出子菜单的问题

1,235 阅读1分钟

今天写react dome 的时候 发现ant menu菜单收起 会弹出来子菜单,但是在官网上显示是没问题的,测试了多遍 发现菜单栏收起的时候 不会单出来子菜单,那么找到问题就去解决问题。

借助官网手风琴dome去解决问题

import { 
 AppstoreOutlined, 
 ContainerOutlined, 
 DesktopOutlined,  
 MailOutlined, 
 MenuFoldOutlined,  
 MenuUnfoldOutlined, 
 PieChartOutlined,  }
 from '@ant-design/icons'; 
 import { Button, Menu } from 'antd';
 import { useState } from 'react';  
function getItem(label, key, icon, children, type) {
    return {key, icon, children, label,  type }; 
}    
const items = [   
     getItem('Option 1', '1', <PieChartOutlined />),   
     getItem('Option 2', '2', <DesktopOutlined />),    
     getItem('Option 3', '3', <ContainerOutlined />),    
     getItem('Navigation One', 'sub1', <MailOutlined />,
     [getItem('Option 5', '5'),  getItem('Option 6', '6'),
     getItem('Option 7', '7'),  getItem('Option 8', '8'),    ]),   
     getItem('Navigation Two', 'sub2', <AppstoreOutlined />, [
     getItem('Option 9', '9'),      getItem('Option 10', '10'),
     getItem('Submenu', 'sub3', null, [getItem('Option 11', '11'),
     getItem('Option 12', '12')]),    ]),  ]; 
 const rootSubmenuKeys = ['sub1', 'sub2'];   //初始数据 
 const MenuBar = () => {   
         const [collapsed, setCollapsed] = useState(false);    
         const [logOpen,setLogOpen] = useState('');   
         const toggleCollapsed = () => {    
                 if(!collapsed){     
                     setLogOpen(openKeys) //记录 关闭时候的openKeys     
                     setOpenKeys([])      
                  }    
                 if(collapsed)   setOpenKeys(logOpen) //打开还原 openKeys    
                  setCollapsed(!collapsed);   
         };    
        const [openKeys, setOpenKeys] = useState(['sub1']);    
        const onOpenChange = (keys) => {
        // 这串代码是手风琴模式,只展开一个菜单
              const latestOpenKey = keys.find((key) => openKeys.indexOf(key) === -1);   
              if (rootSubmenuKeys.indexOf(latestOpenKey) === -1) {       
                     setOpenKeys(keys);     
                 } else {      
                  setOpenKeys(latestOpenKey ? [latestOpenKey] : []);     
                 }
         // 不需要手风琴 把上面代码注释掉
        //保留   setOpenKeys(keys); 
       };       
 return (   
   <div        
        style={{width: 256,}}>  
      <Button  type="primary"  
        onClick={toggleCollapsed}    
        style={{marginBottom: 16,}}  >            
        {collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}      
      </Button>   
     <Menu  
        mode={'inline'}   
        theme="dark" 
        openKeys={openKeys}  
        onOpenChange={onOpenChange}  
        inlineCollapsed={collapsed} 
        items={items}       
      />    
      </div>   
     ); 
 };   
 export default MenuBar;

如果还是侧边栏弹出 那就直接隐藏吧   加到引入的css 里面

  .ant-menu-submenu-popup{    overflow: hidden !important;  }