antd react-router 导航菜单刷新高亮
我当前版本
"antd": "^3.16.5",
"react": "^16.8.6",
"react-router": "^5.0.0",
刷新高亮当前导航位置
app.js
注意一些点:
withRouter
需被包含在<Router>
里,否则会报错的
import React, {Component} from 'react';
import {BrowserRouter as Router, Route, Link ,withRouter} from 'react-router-dom';
import PropTypes from 'prop-types'; //这个选择性安装,我看别人安装了,但是实际经我测试似乎没有用到
import {
Layout, Menu, Icon,Row,Col
} from 'antd';
import './App.css';
const {
Header, Content, Footer, Sider,
} = Layout;
const SubMenu = Menu.SubMenu;
...此处省略部分代码...
class App extends Component {
...此处省略部分代码...
//这个就是前面注释说的,我给注释掉了,经我测试没发现有什么效果,但是官方也有这段代码
/*static propTypes = {
location: PropTypes.object.isRequired
}
*/
render() {
return (
<div className="App">
<Layout style={{minHeight: '100vh'}}>
<Sider
collapsible
collapsed={this.state.collapsed}
onCollapse={this.onCollapse}
>
<div className="logo" style={{textAlign: 'center'}}>
管理系统
</div>
<Menu theme="dark"
selectedKeys={[this.props.location.pathname]}
mode="inline">
<Menu.Item key="/">
<Icon type="home" />
<span>
首页
</span>
</Menu.Item>
<SubMenu
key="sub1"
title={<span><Icon type="area-chart" /><span>客户管理</span></span>}
>
<Menu.Item key="/ClientList"><Link to="/ClientList">客户列表</Link></Menu.Item>
<Menu.Item key="/ClientAdd"><Link to="/ClientAdd">添加客户</Link></Menu.Item>
</SubMenu>
<SubMenu
key="sub2"
title={<span><Icon type="area-chart" /><span>商品管理</span></span>}
>
<Menu.Item key="/GoodsList"><Link to="/GoodsList">商品列表</Link></Menu.Item>
<Menu.Item key="/GoodsAdd" ><Link to="/GoodsAdd">添加商品</Link></Menu.Item>
</SubMenu>
...此处省略部分代码...
</Menu>
</Sider>
...此处省略部分代码...
</Layout>
</div>
);
}
}
export default withRouter(App);
index.js
我主要内容都在app.js
里,由于withRouter
,必须被包含在Router
标签里面,无奈在index.js
添加上router标签
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import {BrowserRouter as Router, Route, Link ,withRouter} from 'react-router-dom';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<Router>
<App />
</Router>
, document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();