封装一个路由,以后我们再使用的时候,不用一个一个写Route那些,只需要调用自己写的方法,并且只需要改动一个文件引入需要的组件就可以了。
views文件夹下新建router文件夹,里面新建RouterView.js和router.config.js
router.config.js配置路由需要的组件以及路径
import Home from '../views/Home'
import Find from '../views/Find'
import Video from '../views/Video'
import My from '../views/My'
import Attention from '../views/Home/Attention'
import Recommend from '../views/Home/Recommend'
import Funny from '../views/Home/Recommend/Children/Funny'
import Hot from '../views/Home/Recommend/Children/Hot'
import Detail from '../views/Detail'
const routes = [
{
from: '/',
to: '/home'
},
{
path: '/home',
component: Home,
children: [
{
from: '/',
to: '/home/attention'
},
{
path: '/home/attention',
component: Attention
},
{
path: '/home/recommend',
component: Recommend,
children: [
{
from: '/home/recommend',
to: '/home/recommend/Hot'
},
{
path: '/home/recommend/Funny',
component: Funny
},
{
path: '/home/recommend/Hot',
component: Hot
},
]
},
{
path: '/home/Video',
component: Video
},
{
path: '/home/Find',
component: Find
},
{
path: '/home/My',
component: My
},
]
},
{
path: '/Detail',
component: Detail
}
]
export default routes
RouterView.js这个文件是根据router-config.js路由配置文件来加载对应的组件的
import React, { Component } from 'react'
import {Switch,Route,Redirect} from 'react-router-dom'
class RouterView extends Component{
render(){
const {routes} = this.props
const normalRoutes = routes.filter(item=>!item.to)
const redirectRoutes = routes.filter(item=>item.from).map((item,index)=><Redirect key={index} from={item.from} to={item.to}/>)
return (
<Switch>
{
normalRoutes&&normalRoutes.map((item,index)=><Route key={index} path={item.path}
render={(props)=><item.component {...props} routes={item.children}/>}
/>).concat(redirectRoutes)
}
</Switch>
)
}
}
export default RouterView
App.js
import React from 'react';
import { BrowserRouter as Router} from 'react-router-dom'
import './App.css';
import routes from './router/router.config'
import RouterView from './router/RouterView'
function App() {
return (
<Router>
<div className="App">
<RouterView routes={routes}/>
</div>
</Router>
);
}
export default App;
views/Home/index.js:
import React, { Component } from 'react'
import TabBottom from '../../components/TabBottom/index'
import RouterView from '../../router/router.view'
export default class index extends Component {
render() {
// console.log(this.props)
return (
<div>
<div className="content">
<RouterView routes={this.props.routes} />
<TabBottom />
</div>
</div>
)
}
}
components/TabBottom/index.js:
import React, { Component } from 'react'
import { NavLink } from 'react-router-dom'
export default class index extends Component {
render() {
return (
<div>
<ul className="NavBottom">
<li><NavLink to='/home'>首页</NavLink></li>
<li><NavLink to='/home/Video'>视频</NavLink></li>
<li><NavLink to='/home/Find'>发现</NavLink> </li>
<li><NavLink to='/home/Message'>消息</NavLink></li>
<li><NavLink to='/home/My'>我</NavLink></li>
</ul>
</div>
)
}
}
版权声明:本文为sakura_zr原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。