模块化react-router配置方法详解
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了模块化react-router配置方法详解,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2797字,纯文字阅读大概需要4分钟。
内容图文
react-router模块化配置
因为公司的需要最近踏进了react坑,一直在挖坑填坑,在路由这一块折腾得不行。
直接进入主题,配置react-router模块化
1.先下载react-router-dom
npm install react-router-dom --save
2.在相应的文件引入react-router-dom相应的模块
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
3.在src子创建一个module目录,接着在module目录在创建一个router.js文件,用来配置路由。
//router.js import Index from '../components/Index' import New from '../components/New' import NewList from '../components/NewList' import NewContent from '../components/NewContent' const routes = [ { path:"/", component:Index, exact:true }, { path:"/new", component:New, routes:[ { path:"/new/", component:NewContent }, { path:"/new/newList", component:NewList } ] }, ] export default routes
4.在app.js根目录添加相应的跳转路径。
//app.js import React from 'react'; import './App.css'; import { BrowserRouter as Router, Route, Link } from "react-router-dom"; import router from "./modules/routers" function App() { return ( <Router> <nav className="nav"> <ul> <li> <Link to="/">首页</Link> </li> <li> <Link to="/new">新闻</Link> </li> </ul> </nav> { router.map((router,index)=>{ if(router.exact){ return <Route exact key={index} path={router.path} render = { props =>( <router.component {...props} routes = {router.routes}/> ) } /> }else{ return <Route key={index} path={router.path} render = { props =>( <router.component {...props} routes = {router.routes} /> ) } /> } }) } </Router> ); } export default App;
注意点:嵌套路由千万不要在<Route/>身上加上component={xxx.xxx},否则在子路由页码就接受不到父路由传递给子路由的数据,重要的事情说三篇
注意点:嵌套路由千万不要在<Route/>身上加上component={xxx.xxx},否则在子路由页码就接受不到父路由传递给子路由的数据,重要的事情说三篇
注意点:嵌套路由千万不要在<Route/>身上加上component={xxx.xxx},否则在子路由页码就接受不到父路由传递给子路由的数据,重要的事情说三篇
解析一下,<Route/>里面的render,这是官方给出的一种固定写法,为了解决父路由传递数据给子路由接受不到的问题。render是一个对象,里面是一个箭头函数,箭头函数放回<router.component {...props} routes = {router.routes} />一个标签,router.component的router对于的是你map传进来的那个形参,传啥写啥;component 是配置文件对应的component ,routes 是传给子路由的数据、(子路由通过this.props.routes 接收)
5.在有子路由的页码配置跳转
import React ,{Component} from 'react'; import { BrowserRouter as Router, Route, Link } from "react-router-dom"; class New extends Component{ render(){ return( <div className="box"> <div className="left"> <ul> <li> <Link to="/new">New</Link> </li> <li> <Link to="/new/newList">NewList</Link> </li> </ul> </div> <div className="right"> { this.props.routes.map((item,index)=>{ return <Route key={index} exact path={item.path} component={item.component}></Route> }) } </div> </div> ) } } export default New
最后的结果为:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
内容总结
以上是互联网集市为您收集整理的模块化react-router配置方法详解全部内容,希望文章能够帮你解决模块化react-router配置方法详解所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。