如何管理多个导航项状态?

时间:2019-06-25 19:29:21

标签: javascript reactjs antd

我正在尝试使用antd组件来实现水平菜单。

单击nav项目时,子菜单显示不正确。

Codesandbox demo

enter image description here

const MenuList = [
  {
    name: "Navigation two - Submenu",
    subMenuRoutes: [
      {
        name: "A- item1",
        url: "/item1Url1"
      },
      {
        name: "A - item2",
        url: "/item1Url2"
      }
    ]
  },
  {
    name: "Navigation Three - Submenu",
    subMenuRoutes: [
      {
        name: "B- item1",
        url: "/item1Url1"
      },
      {
        name: "B - item2",
        url: "/item1Url2"
      }
    ]
  }
];

function TextAreaManager() {
  const [showMenu, setShowMenu] = useState(false);
  return (
    <Tabs onTabClick={() => setShowMenu(prev => !prev)}>
      {MenuList.map(item => {
        return (
          <TabPane
            tab={
              <>
                <Icon type="setting" />
                {item.name}
                <Icon
                  type={showMenu ? "up" : "down"}
                  style={{ marginLeft: "10px" }}
                />
              </>
            }
          >
            {showMenu && (
              <Menu>
                {item.subMenuRoutes.map(childItem => {
                  return (
                    <Menu.Item key={childItem.url}>{childItem.name}</Menu.Item>
                  );
                })}
              </Menu>
            )}
          </TabPane>
        );
      })}
    </Tabs>
  );

1 个答案:

答案 0 :(得分:2)

有一些问题需要处理:

  1. 为每个数组项分配唯一键,以便正确呈现组件。

    menuList.map(item => <TabPane key={item.name}></TabPane>);

  2. 您需要管理每个菜单的状态,才能正确显示带有相应图标showMenuManager[item.name]的菜单:

<Tabs
  onTabClick={e =>
    setShowMenuManager(prev => {
      const newState = { ...initMenuState, [e]: !prev[e] };
      console.log(newState);
      return newState;
    })
  }
/>;
const initMenuState = {
 "Navigation two - Submenu": false,
 "Navigation Three - Submenu": false
};

function TopMenuManager() {
 const [showMenuManager, setShowMenuManager] = useState(initMenuState);
 return (
   <Tabs ... >
     {menuList.map(item => (
       <TabPane
         key={item.name}
         tab={
           <>
             ...
             <Icon
               type={showMenuManager[item.name] ? "up" : "down"}
             />
           </>
         }
       >
         {showMenuManager[item.name] && ...}
       </TabPane>
     ))}
   </Tabs>
 );
}

检查最终的example和分叉的沙箱:

Edit Q-56637369-AntdTopMenuManage