pro 菜單高亮
通常在項(xiàng)目中無(wú)法保持路由層級(jí)的嵌套關(guān)系, props.children
的渲染很多情況下并不方便,這時(shí)候?yàn)榱吮3肿髠?cè)菜單欄的高亮狀態(tài),有兩種方式可以實(shí)現(xiàn)。
文章轉(zhuǎn)自我的語(yǔ)雀:https://www.yuque.com/liuyin-zzwa0/ada6ao/dvpky4
無(wú)侵入式
path
的寫法注意按照 url 的層級(jí)就可以實(shí)現(xiàn)。
{
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){ // 菜單展開(kāi)并存在自定義歸屬路徑
const selfSelectedKeys = this.getSelectedMenuKeys(ascriptionPathname);
const notEmpty = [selectedKeys.filter(a => !!a), selfSelectedKeys.filter(a => !!a)];
// 保證一級(jí)菜單相同,但是應(yīng)該有更合適的判斷方式,根據(jù)實(shí)際情況來(lái)改
if(openKeys[0] === selfSelectedKeys[0] && notEmpty[0].length < notEmpty[1].length){
selectedKeys = selfSelectedKeys;
}
}
if (!selectedKeys.length && openKeys) {
selectedKeys = [openKeys[openKeys.length - 1]];
}
- 在頁(yè)面組件中調(diào)用
setAscriptionPathname
方法
componentDidMount() {
const { dispatch } = this.props;
dispatch({
type: 'base/setAscriptionPathname',
payload: 'lexicon/index', // 這里放router.js|| router.config.js 里的菜單項(xiàng)中的 path
})
}