React是个技术栈,单单使用React很难构建复杂的Web应用程序,很多情况下我们需要引入其他相关的技术

React Router是React的路由库,保持相关页面部件与URL间的同步

下面就来简单介绍其基础使用,更全面的可参考 指南

1. 它看起来像是这样

在页面文件中

在外部脚本文件中

2. 库的引入

React Router库的引入,有两种方式

2.1 浏览器直接引入

可以引用 这里 的浏览器版本,或者下载之后引入

然后就可以直接使用 ReactRouter 这个对象了,我们可能会使用到其中的几个属性

  1. let {Router, Route, IndexRoute, Redirect, IndexRedirect, Link, IndexLink, hashHistory, browserHistory} = ReactRouter;

2.2 npm 安装,通过构建工具编译引入

  1. npm install --save react-router

安装好路由库之后,在脚本文件中引入相关属性

  1. import {Router, Route, IndexRoute, Redirect, IndexRedirect, Link, IndexLink, hashHistory, browserHistory} from 'react-router';

因浏览器目前还不能支持import与export命令,且babel工具不会将require命令编译,所以我们还得需要如Webpack等构建工具编译引入

库引入之后,在ReactDOM的render方法中,就可以使用相关的组件了

3. 路由简单使用

最基本的,通过URL判断进入哪个页面(组件部件)

  1. class First extends Component {
  2. constructor(props) {
  3. super(props);
  4. }
  5.  
  6. render() {
  7. return <p>First</p>
  8. }
  9. }
  10.  
  11. class Second extends Component {
  12. constructor(props) {
  13. super(props);
  14. }
  15.  
  16. render() {
  17. return <p>Second</p>
  18. }
  19. }
  20.  
  21. class App extends Component {
  22. constructor(props) {
  23. super(props);
  24. }
  25.  
  26. render() {
  27. return <div></div>
  28. }
  29. }
  1. render((
  2. <Router history={hashHistory}>
  3. <Route path="/" component={App} />
  4. <Route path="first" component={First} />
  5. <Route path="second" component={Second} />
  6. </Router>
  7. ),
  8. document.getElementById('box')
  9. );

首先,Router是一个容器,history属性定义了是用何种方式处理页面的URL

有三种

  • browserHistory:通过URL的变化改变路由,是推荐的一种方式,但是需要在服务器端需要做一些配置(窝目前还不知怎么配)
  • hashHistory:通过#/ ,其实就像是单页面应用中常见的hashbang方式,example.com/#/path/path.. (使用简单,这里暂且就用这种方式)
  • createMemoryHistory:Memory history 并不会从地址栏中操作或是读取,它能够帮助我们完成服务器端的渲染,我们得手动创建history对象

然后,在容器中使用Route组件定义各个路由,通过path指定路径(可以看到,是不区分大小写的),通过component指定该路径使用的组件

也可以直接在Router容器上直接用routes属性定义各个路由,如

  1. let routes =
  2. <div>
  3. <Route path="/" component={App} />
  4. <Route path="first" component={First} />
  5. <Route path="second" component={Second} />
  6. </div>;
  7.  
  8. render(<Router routes={routes} history={hashHistory}></Router>, document.getElementById('box'));

需要注意的是{routes}中只能有一个父级,所以这里加了<div>标签

另外,路由Route也可以嵌套,在上面的例子中,嵌套起来可能更符合实际情况

需要注意的是,这里的App在父级,为了获取子级的First与Second组件,需要在App组件中添加 this.props.children 获取

  1. class App extends Component {
  2. constructor(props) {
  3. super(props);
  4. }
  5.  
  6. render() {
  7. return <div>{this.props.children}</div>
  8. }
  9. }
  10.  
  11. render((
  12. <Router history={hashHistory}>
  13. <Route path="/" component={App}>
  14. <Route path="first" component={First} />
  15. <Route path="second" component={Second} />
  16. </Route>
  17. </Router>
  18. ),
  19. document.getElementById('box')
  20. );

同样的,可以直接在Router中用routes属性定义路由

  1. let routes =
  2. <Route path="/" component={App}>
  3. <Route path="first" component={First} />
  4. <Route path="second" component={Second} />
  5. </Route>;
  6.  
  7. render(<Router routes={routes} history={hashHistory}></Router>, document.getElementById('box'));

4. 路由的其他组件

除了基本的Route之外,IndexRoute、Redirect、IndexRedirect、Link、IndexLink等,顾名思义

  • IndexRoute: 在主页面会用到,如上个例子中,在路径"/"下我们看到的是空白页面,可以添加默认的页面组件用于导航
  • Link: 可以认为它是<a>标签在React中的实现,使用to属性定义路径,还可以通过activeClass或activeStyle定义active的样式
  • IndexLink: 类似Link,推荐用来定义指向主页面的链接,当然也可以随意定义

  1. class First extends Component {
  2. constructor(props) {
  3. super(props);
  4. }
  5.  
  6. render() {
  7. return (
  8. <p>First
  9. <IndexLink to="/" activeStyle={{color: 'red'}}>Basic</IndexLink>
  10. </p>
  11. )
  12. }
  13. }
  14.  
  15. class Second extends Component {
  16. constructor(props) {
  17. super(props);
  18. }
  19.  
  20. render() {
  21. return <p>Second</p>
  22. }
  23. }
  24.  
  25. class Basic extends Component {
  26. constructor(props) {
  27. super(props);
  28. }
  29.  
  30. render() {
  31. return (
  32. <ul role="nav">
  33. <li><IndexLink to="/" activeStyle={{color: 'red'}}>Basic</IndexLink></li>
  34. <li><Link to="/first" activeStyle={{color: 'red'}}>First</Link></li>
  35. <li><Link to="/Second" activeClass="active">Second</Link></li>
  36. </ul>
  37. )
  38. }
  39. }
  40.  
  41. class App extends Component {
  42. constructor(props) {
  43. super(props);
  44. }
  45.  
  46. render() {
  47. return <div>
  48. {this.props.children}
  49. </div>
  50. }
  51. }
  52.  
  53. render((
  54. <Router history={hashHistory}>
  55. <Route path="/" component={App}>
  56. <IndexRoute component={Basic} />
  57. <Route path="first" component={First} />
  58. <Route path="second" component={Second} />
  59. </Route>
  60. </Router>
  61. ),
  62. document.getElementById('box')
  63. );
  • Redirect: 从from路径重定向到to路径
  • IndexRedirect: 在主页面,直接重定向到to路径

  1. render((
  2. <Router history={hashHistory}>
  3. <Route path="/" component={App}>
  4. <IndexRoute component={Basic} />
  5. <IndexRedirect to="first" />
  6. <Redirect from="second" to="first" />
  7. <Route path="first" component={First} />
  8. <Route path="second" component={Second} />
  9. </Route>
  10. </Router>
  11. ),
  12. document.getElementById('box')
  13. );

5. 路由的path规则

path定义的路由的路径,在hashHistory中,它的主页路径是#/

自定义Route路由通过与父Route的path进行合并,在与主页路径合并,得到最终的路径

path的语法

  • :paramName 匹配 URL 的一个部分,直到遇到下一个/、?、#
  • () 表示URL的这个部分是可选的
  • * 匹配任意字符(非贪婪模式),直到模式里面的下一个字符为止
  • ** 匹配任意字符(贪婪模式),直到下一个/、?、#为止
  1. <Route path="/hello/:name"> // 匹配 /hello/michael 和 /hello/ryan
  2. <Route path="/hello(/:name)"> // 匹配 /hello, /hello/michael, 和 /hello/ryan
  3. <Route path="/files/*.*"> // 匹配 /files/hello.jpg 和 /files/hello.html
  4. <Route path="/**/*.jpg"> // 匹配 /files/hello.jpg 和 /files/path/to/file.jpg

而:name可以通过 this.props.params 中取到

  1. class First extends Component {
  2. constructor(props) {
  3. super(props);
  4. }
  5.  
  6. render() {
  7. return (
  8. <p>First {this.props.params.name}
  9. <IndexLink to="/" activeStyle={{color: 'red'}}>Basic</IndexLink>
  10. </p>
  11. )
  12. }
  13. }
  14.  
  15. .
  16. .
  17.  
  18. <Route path="/:name" component={First} />

通过React Dev Tool也可以看到组件的相关数据

6. 路由的onEnter、onLeave钩子

在路由的跳转中,我们可能需要在进入页面或离开页面的时候做一些特殊操作,Route 通过 onEnter 与 onLeave 定义了这两个行为

  1.   <Route path="first" component={First} onEnter={(nextState, replace) => {
  2. console.log(nextState);
  3. alert('onEnter');
  4. // replace('second');
  5. }} onLeave={() => {
  6. alert('onLeave');
  7. }}/>

如上,带两个参数,通过 replace 可以更新路径,把注释去掉后,进入"/first"时立马跳转值"/second",这在检测登录时应该比较有用

更多的使用参见 指南

React Router基础教程的更多相关文章

  1. [转] React Router 使用教程

    PS:react-route就是一个决定生成什么父子关系的组件,一般和layout结合起来,保证layout不行,内部的子html进行跳转 你会发现,它不是一个库,也不是一个框架,而是一个庞大的体系. ...

  2. React Router基础使用

    React是个技术栈,单单使用React很难构建复杂的Web应用程序,很多情况下我们需要引入其他相关的技术 React Router是React的路由库,保持相关页面部件与URL间的同步 下面就来简单 ...

  3. React Router 使用教程

    一.基本用法 React Router 安装命令如下. $ npm install -S react-router 使用时,路由器Router就是React的一个组件. import { Router ...

  4. React-Native基础教程

    React-Native牛刀小试仿京东砍啊砍砍到你手软 React-Native基础教程 *React-Native基础篇作者git *React-Native官方文档 *Demo 几个月前faceb ...

  5. React Router教程

    React Router教程 React项目的可用的路由库是React-Router,当然这也是官方支持的.它也分为: react-router 核心组件 react-router-dom 应用于浏览 ...

  6. React Native基础&入门教程:初步使用Flexbox布局

    在上篇中,笔者分享了部分安装并调试React Native应用过程里的一点经验,如果还没有看过的同学请点击<React Native基础&入门教程:调试React Native应用的一小 ...

  7. React实例入门教程(1)基础API,JSX语法--hello world

      前  言 毫无疑问,react是目前最最热门的框架(没有之一),了解并学习使用React,可以说是现在每个前端工程师都需要的. 在前端领域,一个框架为何会如此之火爆,无外乎两个原因:性能优秀,开发 ...

  8. 【原创】React实例入门教程(1)基础API,JSX语法--hello world

    前  言 毫无疑问,react是目前最最热门的框架(没有之一),了解并学习使用React,可以说是现在每个前端工程师都需要的. 在前端领域,一个框架为何会如此之火爆,无外乎两个原因:性能优秀,开发效率 ...

  9. React Router学习

    React Router教程 本教程引用马伦老师的的教程 React项目的可用的路由库是React-Router,当然这也是官方支持的.它也分为: react-router 核心组件 react-ro ...

随机推荐

  1. excel查找某一列的值在、不在另一列中

    统计中遇到找出一列的值不在另一列的需求: 找出A列中不在B列的值 方法如下: 使用countif函数 比如找出A列中不在B列的值: 在C1中输入 COUNTIF(B:B,A1) 下拉单元格,在首行添加 ...

  2. Dnsmasq安装与配置-搭建本地DNS服务器

    默认的情况下,我们平时上网用的本地DNS服务器都是使用电信或者联通的,但是这样也导致了不少的问题,首当其冲的就是上网时经常莫名地弹出广告,或者莫名的流量被消耗掉导致网速变慢.其次是部分网站域名不能正常 ...

  3. 关于CentOS下 yum包下载下的rpm包放置路径

    在CentOS下用yum安装,回发现在/var/cache/yum/下的base.extrs和updates下的packages下都没有发现下载的RPM 原来在/etc/yum.conf下没有设置下载 ...

  4. 在.net中使用ETW事件的方法

    直到.net4.5,才有了比较便利的操作ETW的方法. 本文介绍的方法主要来源于Microsoft.Diagnostics.Tracing.TraceEvent官方资料库. 准备 (1)需要用到类:M ...

  5. gcc 6.0编译opencv出错

    在编译opencv3.2时候,出现下面错误: cmake -DCMAKE_BUILD_TYPE=RELEASE -DCMAKE_INSTALL_PREFIX=/usr/local -DBUILD_NE ...

  6. 动态生成html元素并为元素追加属性

    动态生成HTML元素的方法有三种: 第一种:document.createElement()创建元素,再用appendChild( )方法将元素添加到指定节点 <!DOCTYPE html> ...

  7. 阿里云ECS 介绍

    1.阿里云产品概述 1 2.阿里云基础架构介绍 2 3. ECS产品概念和功能 6 4. ECS运维管理和API 12 1.阿里云产品概述 2.阿里云基础架构介绍 ECS 主要有五个主要的组成部分 作 ...

  8. InfluxDB Java入门

    添加依赖 <dependency> <groupId>org.influxdb</groupId> <artifactId>influxdb-java& ...

  9. 【重要通知】本人所有技术文章转移至https://zzqcn.github.io

    本人所有技术文章转移至 https://zzqcn.github.io

  10. sublime text3: markdown 安装及常用语法简介

    自己上传到 github 上的 README.rdm 文件内容显示没有“美化”,所有内容都挤在一块儿了,很不舒服. 原因是:github 的文档 README.rdm 文件使用 markdown 编辑 ...