react-router-view
v1.0.7
Published
this is a component for react-router-dom
Downloads
10
Readme
ReactRouterView
RouterView是react-router-dom 4.0的一个组件,该组件实现了用对象配置路由,可以在一个js文件中配置所有路由,在需要显示路由视图的地方直接使用RouterView组件代替,该组件有一个routes属性,routes是一个数组,即路由的配置,相对于react-router4.0官方的使用方法,大大简化了项目中的代码,使路由的配置更清晰、直观。
使用方法:
安装
npm i react-router-view --save
使用示例
示例1:在BrowserRouter组件中直接使用RouterView组件,把路由的配置通过routes属性传到组件中
import React, {Component} from 'react';
import {BrowserRouter} from 'react-router-dom';
import RouterView from "react-router-view"; // 导入react-router-view
import getRoutes from "./common/routerConfig";
const routes = getRoutes()//路由的配置,
function App(props) {
return (
<BrowserRouter>
<RouterView routes={routes}></RouterView>
</BrowserRouter>
)
}
export default App;
示例2:比如 "/" 匹配到的组件是Layout, "/home"是"/"子路由,"/home"匹配到的组件Home要在Layout中渲染,如下, 在需要渲染Home组件的地方使用RouterView组件,在Layout组件的props中可以拿到 "/" 的子路由childRoutes,把子路由的数据通过routes属性传到RouterView组件中,当跳转到 "/home"的时候,RouterView组件的位置就会显示"/home"匹配到的Home组件,多层嵌套的路由也是如此
import React from 'react';
import RouterView from "react-router-view";
function Layout(props) {
return (
<div>首页</div>
<div>
<RouterView routes={this.props.childRoutes}></RouterView>
</div>
)
}
export default Layout;
示例3:路由配置规则如下
import {asyncComponent} from "./asyncComponent";
const Layout = asyncComponent(() => import ("@/layout"));
const Home = asyncComponent(() => import ("@/routes/home"));
const List = asyncComponent(() => import ("@/routes/list"));
const Details = asyncComponent(() => import ("@/routes/details"));
export default function () {
const routes = [
{
path: "/", // url
component: Layout, //url匹配的组件
redirect: "/home", // 把 "/" 重定向到 "/home"
childRoutes: [ // "/"的子路由
{
path: "/home",
component: Home,
}, {
path: "/list",
component: List,
childRoutes: [ // "/list"的子路由
{
path: "/list/:id", // 动态路由
component: Details
}
]
}
]
}
]
return routes;
}