pro 菜单高亮
通常在项目中无法保持路由层级的嵌套关系, props.children
的渲染很多情况下并不方便,这时候为了保持左侧菜单栏的高亮状态,有两种方式可以实现。
无侵入式
path
的写法注意按照 url 的层级就可以实现。
{
path: '/base',
name: 'base',
icon: 'bars',
routes: [
{
path: '/base/',
name: 'index',
component: './Base/Index'
},
{
path: '/base/edit/',
name: 'detail',
component: './Base/Edit',
hideInMenu: true,
},
],
},
侵入式
修改SiderMenu组件
- 修改
models/base.js
文件,添加如下代码
reducers: {
// ... 省略
setAscriptionPathname(state, action){
return {
...state,
ascriptionPathname: action.payload
}
}
}
- 修改
src\layouts\BasicLayout.js
export default connect(({ base, setting, menu }) => ({
Company: base.company,
collapsed: base.collapsed,
layout: setting.layout,
routerMap: menu.routerMap,
menuData: menu.menuData,
breadcrumbNameMap: menu.breadcrumbNameMap,
...setting,
ascriptionPathname: base.ascriptionPathname,
}))(props => (
<Media query="(max-width: 599px)">
{isMobile => <BasicLayout {...props} isMobile={isMobile} />}
</Media>
));
- 修改
SilderMenu/BaseMenu.js
文件,添加如下代码
import { getMenuMatches, getAscriptionPathname } from './SiderMenuUtils';
// ... 省略中间代码
let selectedKeys = this.getSelectedMenuKeys(pathname);
if(openKeys && !!this.props.ascriptionPathname){ // 菜单展开并存在自定义归属路径
const selfSelectedKeys = this.getSelectedMenuKeys(ascriptionPathname);
const notEmpty = [selectedKeys.filter(a => !!a), selfSelectedKeys.filter(a => !!a)];
// 保证一级菜单相同,但是应该有更合适的判断方式,根据实际情况来改
if(openKeys[0] === selfSelectedKeys[0] && notEmpty[0].length < notEmpty[1].length){
selectedKeys = selfSelectedKeys;
}
}
if (!selectedKeys.length && openKeys) {
selectedKeys = [openKeys[openKeys.length - 1]];
}
- 在页面组件中调用
setAscriptionPathname
方法
componentDidMount() {
const { dispatch } = this.props;
dispatch({
type: 'base/setAscriptionPathname',
payload: 'lexicon/index', // 这里放router.js|| router.config.js 里的菜单项中的 path
})
}