认识
使用
标准使用
细节
- 默认选中: 通过
defaultSelectedKeys
属性实现 - 通过
defaultSelected
状态控制菜单渲染
- 细节一: 菜单为异步获取,如果直接渲染菜单,导致
defaultSelectedKeys
作用失效,所以当defaultSelected.length
有数据时在渲染菜单
- 通过
Fragment
作为包裹容器
- 细节一: 因为已经设置了
Menu
的样式,不想再有外层标签包裹了,所以通过Fragment
包裹
/* eslint-disable */
import React, { useState, useEffect,Fragment } from "react";
import { Menu as MenuAntd } from "antd";
import { connect } from "react-redux";
import api from "../../api/index";
import {
currentMenuReducerChange,
currentTabReducerChange,
} from "../../store/action/nav";
function Menu(props) {
const [menuList, setMenuList] = useState([]);
const [defaultSelected, setDefaultSelected] = useState([]);
const { currentTab, currentMenu } = props;
useEffect(async () => {
const { data = [] } = await api["directoryList_" + currentTab]();
setMenuList(data);
props.currentMenuReducerChange(data[0]);
setDefaultSelected(data[0]);
}, []);
const handleClickMenu = async (value) => {
props.currentMenuReducerChange(value);
};
const menuRender = () => {
return (
<MenuAntd mode="inline" defaultSelectedKeys={defaultSelected} >
{
menuList.map((value) => (
<MenuAntd.Item key={value} onClick={() => handleClickMenu(value)}>
{value}
</MenuAntd.Item>
))
}
</MenuAntd>
)
}
return (
<Fragment>
{
defaultSelected.length && menuRender()
}
</Fragment>
)
}
const mapStateToProps = (state) => {
return {
currentTab: state.currentTab,
currentMenu: state.currentMenu,
};
};
const mapDispatchToProps = {
currentMenuReducerChange,
currentTabReducerChange,
};
const ConnectMenu = connect(mapStateToProps, mapDispatchToProps)(Menu);
export default ConnectMenu;