前提
- 了解react框架
- 熟悉jsx语法
- 有react-router-dom插件使用基础
react路由封装
在react项目下src目录下新建router文件夹,router文件目录下新建index.js和config.js
- router/config.js ----生成并抛出路由配置表
// 引入路由视图组件 import Index from '../views/Index' import Movie from '../views/two/Movie' import Place from '../views/two/Place' import My from '../views/two/My' // 路由配置表 数组 const routes=[ { path:'/index', component:Index, children:[ { path:'/index/movie', component: Movie }, { path:'/index/place', component: Place }, { path:'/index/my', component: My } ] } ]; // 抛出路由配置表 export default routes;
- router/index.js 加载路由视图组件的函数组件
// 加载路由视图组件得函数组件 -加载条件-路由路径对应路由视图组件 一一对应得关系 --->获取路由配置表 import React from 'react'; // 引入路由内置组件 import {Route} from 'react-router-dom' const RouterView=(props)=>{ // 函数组件得props属性 console.log(props.routes); // 获取路由配置表 // 一一对应关系 遍历 return props.routes.map((item,index)=>{ // 路由对象 加载路由视图组件 return <Route key={index} path={item.path} render={(routeProps)=>{ // routeProps 路由元信息 // 判断当前得路由对象是否存在子路由 if(item.children){ // 存在路由嵌套 递归函数 return <item.component {...routeProps} routes={item.children}/> }else{ // 不存在路由嵌套 return <item.component {...routeProps}/> } }}/> }) } export default RouterView;
使用
// 根组件 App.js import React, { Component } from 'react' // 引入路由内置组件 import {BrowserRouter} from 'react-router-dom' // 引入加载路由视图得函数组件 import RouterView from './router/index' // 引入路由配置表 import config from './router/config' export default class App extends Component { render() { return ( <div className='App'> <BrowserRouter> {/* 加载/展示路由视图组件 */} <RouterView routes={config}/> </BrowserRouter> </div> ) } }
react路由封装核心-----组件传参/js逻辑/递归函数