用ant Desgin中的侧边布局配合React-router v4完成导航
主要的利用antDesgin官方提供的API来解决,思路是设置defaultSelectedKeys
和selectedKeys
这两个key
与Menu.Item
组件的key
匹配。
<Menu theme='dark'
defaultSelectedKeys={[defaultKey]}
mode='inline'
selectedKeys={[selectedKeys]}
defaultOpenKeys={[defaultKey]}>
{renderList}
</Menu>
其中Menu
组件的属性selectedKeys
和defaultOpenKeys
可以通过React-router的withRouter
来获取当前页面的路径
<Menu.Item key={`/${key}`}>
<NavLink
to={`/${key}`}
activeClassName='selcted'
replace>
<i className={`fa fa-${icon}`} aria-hidden='true'></i>
{name}
</NavLink>
</Menu.Item>
完整组件可以参考如下:
class SideNav extends Component {
constructor(props) {
super(props);
this.keyList = this.keyList.bind(this);
}
keyList() {
return (
showList.map((item) => {
let { key, name, icon, children } = item;
if (children.length) {
return (
<SubMenu
key={`${key}`}
title={
<span>
<i className={`fa fa-${icon}`} aria-hidden='true'></i>
{name}
</span>}>
{children.map((value) => {
return (
<Menu.Item key={`/${key}/${value.key}`}>
<NavLink
to={`/${key}/${value.key}`}
activeClassName='selcted'
replace>
{value.name}
</NavLink>
</Menu.Item>
)
})}
</SubMenu>
)
} else {
// Menu.Item 组件的属性key表示当前路由 当前匹配到当前路由时
return (
<Menu.Item key={`/${key}`}>
<NavLink
to={`/${key}`}
activeClassName='selcted'
replace>
<i className={`fa fa-${icon}`} aria-hidden='true'></i>
{name}
</NavLink>
</Menu.Item>
)
}
})
)
}
render() {
let renderList = this.keyList();
let { pathname } = this.props.history.location;
let pathSplit = pathname.split('/').slice(1);
let selectedKeys = pathSplit.length <= 2 ? `/${pathSplit.join('/')}` : `/${pathSplit[0]}/${pathSplit[1]}`;
// defaultOpenKeys 的值应该是 pathSplit[0]
return (
<Layout>
<Sider style={{ overflow: 'auto', height: '100vh', position: 'fixed', left: 0 }}>
<div className='app-router'>
<div className='logo'>
<img src={require('../../img/png/logo.png')} />
<br />
<span>{USERNAME}</span>
</div>
<nav>
<Menu theme='dark'
defaultSelectedKeys={[defaultKey]}
mode='inline'
selectedKeys={[selectedKeys]}
defaultOpenKeys={[defaultKey]}>
{renderList}
</Menu>
</nav>
</div>
</Sider>
<Layout style={{ marginLeft: 200 }}>
{this.props.children}
</Layout>
</Layout>
);
}
}
SideNav.propTypes = {
children: PropTypes.node,
history: PropTypes.object
};
// 用withRouter传入当前的url
export default withRouter(SideNav);
网友评论