1、首先创建项目 :
npx create-react-app 项目名
2、在项目内下载路由插件:
在这里我下的是5版本,注意版本问题,有些版本不生效
npm i react-router-dom@5 -S
3、页面创建目录:
4、在routerConfig.js内封装一下路由。
import Model1 from "../components/Model1/Model1"
import Model2 from "../components/Model2/Model2"
import Model3 from "../components/Model3/Model3"
import Home from "../pages/Home/Home"
import Second from '../pages/Second/Second'
import Three from "../pages/Three/Three"
// 配置路由文件
let Routes = [
// 普通页面路由设置
{ path: '/', component: Home },
// 子页面路由设置
{
path: '/second', component: Second, children: [
{ path: 'model1', component: Model1 },
{ path: 'model2', component: Model2 },
{ path: 'model3', component: Model3 },
]
},
{ path: '/three', component: Three },
]
export default Routes;
页面效果如下:
5、在router文件夹下的index.js内开始使用
import React, { Component } from 'react';
// HashRouter
import { BrowserRouter, Switch, Route, Redirect } from 'react-router-dom';
// 导入Routes路由信息
import Routes from './routerConfig';
//react 中的路由本质上就是一个组件。
class Index extends Component {
render() {
return (
<BrowserRouter>
<Switch>
{
Routes.map((route, index) => {
// 判断是否存在子路由
if (route.children) {
// 构建子路由
return <Route key={index} path={route.path} children={() => this.createChildRoute(route)} />;
} else {
// 执行里面的代表路由只需要构建一个根路由
return this.createBaseRoute(route, index);
}
})
}
</Switch>
</BrowserRouter>
);
}
// 定义函数完成普通路由的构建
createBaseRoute(route, index) {
return <Route exact path={route.path} component={route.component} key={index}></Route>
}
// 定义函数 ,完成子路由的构建
createChildRoute(route) {
return (
<route.component>
<Switch>
{/* 构建每一个子路由 */}
{route.children.map((route1, index1) => {
// 处理子路由的路径
let route_temp = { ...route1, path: route.path + '/' + route1.path }
// console.log(route_temp);
return this.createBaseRoute(route_temp, index1);
})}
{/* 路由重定向 */}
{
<Redirect from={route.path} to={route.path + '/' + route.children[0].path} />
}
</Switch>
</route.component>
)
}
}
export default Index;
结果:更改上面hash值随意跳转页面。