admin 管理员组文章数量: 887021
注意:使用的版本是
"react": "17.0.2",
"react-dom": "17.0.2",
"react-router-dom": "5.2.0",
步骤如下:
-
1、在src目录下新建 router 文件夹
-
2、在src下新建pages文件夹,新建自己需要的路由体系
-
3、在文件夹中新建 index.js routerView.js routerConfig.js 三个js文件
index.js ( 路由入口文件 以 BrowserRouter 为例 )
import { BrowserRouter } from "react-router-dom"
import routes from "./routerConfig";
import RouterView from "./routerView"
export default function RootRouter() {
return (
<BrowserRouter>
<RouterView routes={routes}></RouterView>
</BrowserRouter>
)
}
routerConfig.js (根据自己的路由配置对应的路由数组)
import Index from "../pages/Index";
import Home from "../pages/Index/home";
import Classify from "../pages/Index/classify";
import Car from "../pages/Index/car";
import My from "../pages/Index/my";
import Login from "../pages/Login";
const routes = [
{
path: "/login",
component: Login,
},
{
path: "/index",
component: Index,
children: [
{
path: "/index/home",
component: Home,
},
{
path: "/index/classify",
component: Classify,
},
{
path: "/index/car",
component: Car,
},
{
path: "/index/my",
component: My,
}
],
},
{
path: "/",
to: "/index/home" // 重定向
}
]
export default routes;
routerView.js
import { Switch, Route, Redirect } from 'react-router-dom'
function RouterView({ routes }) {
const routerArr = routes && routes.filter(item => !item.to);//非重定向的数组
const redirectArr = routes && routes.filter(item => item.to);//重定向的数组
return <Switch>
{
routerArr && routerArr.map((item, index) => <Route key={index} path={item.path} render={(props) => {
return <itemponent {...props} child={item.children} />
}} />)
}
{
redirectArr && redirectArr.map((item, index) => <Redirect key={index} from={item.path} to={item.to} />)
}
</Switch>
}
export default RouterView;
-
4、在app.js中引入路由入口文件
import './App.css';
import RootRouter from './router';
function App() {
return <div className='origin'>
<RootRouter />
</div>
}
export default App;
问题来了,怎么在首次加载的时候显示 /index/home 对应的组件呢?
-
5、在pages文件夹下对应的/index这个jsx文件中写入:
import React from 'react';
import { NavLink } from 'react-router-dom';
import RouterView from '../../router/routerView';
import "./index.css"
export default class Index extends React.Component {
render() {
const { child } = this.props;
return (
<div className='index'>
<div className='main'>
<RouterView routes={child}></RouterView>
</div>
<div className="footer">
<NavLink to="/index/home" activeClassName='active'>首页</NavLink>
<NavLink to="/index/classify">分类</NavLink>
<NavLink to="/index/car">购物车</NavLink>
<NavLink to="/index/my">我的</NavLink>
</div>
</div>
);
}
}
大功告成了! 感谢支持!
版权声明:本文标题:简单react路由表的实现(移动端为例,PC端也适用) 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.freenas.com.cn/jishu/1715799935h651868.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论