在react-router-dom的官方示例中,侧边栏是非常容易实现的一个示例,奇实现的核心就是展示两组Routes。
本示例的效果图如下:
相关的核心代码:
import React, {Component} from 'react';
import {
BrowserRouter as Router,
Route,
Link,
Switch,
Redirect
} from 'react-router-dom';
const routes = [
{ path: '/',
exact: true,
sidebar: () => <div>home!</div>,
main: () => <h2>Home</h2>
},
{ path: '/bubblegum',
sidebar: () => <div>bubblegum!</div>,
main: () => <h2>Bubblegum</h2>
},
{ path: '/shoelaces',
sidebar: () => <div>shoelaces!</div>,
main: () => <h2>Shoelaces</h2>
}
]
class App extends Component {
constructor(props) {
super(props);
}
render() {
return (
<Router>
<div style={{display:'flex'}}>
<div style={{width: '200px',backgroundColor: '#cccccc'}}>
<ul>
<li><Link to='/'>Home</Link></li>
<li><Link to='/bubblegum'>Bubblegum</Link></li>
<li><Link to='/shoelaces'>Shoelaces</Link></li>
</ul>
{
routes.map((item,index)=>{
return (
<Route exact={item.exact} key={index} path={item.path} component={item.sidebar}/>
)
})
}
</div>
<div style={{flex: 1}}>
{
routes.map((item,index)=>{
return (
<Route exact={item.exact} key={index} path={item.path} component={item.main}/>
)
})
}
</div>
</div>
</Router>
);
}
}
export default App;
总体的实现思路:
是比较简单的路由方式,一个Link组件对应两个Route组件,一个在侧边栏区域,一个在右边的主视图区域。
Route的展示是通过对routes数组进行两次map遍历得到的!
本示例的github地址:https://github.com/liwudi/react-router-dom8.git