React Router基础使用


Posted in Javascript onJanuary 17, 2017

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

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

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

1. 它看起来像是这样

在页面文件中

 React Router基础使用

在外部脚本文件中

 React Router基础使用

 React Router基础使用

2. 库的引入

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

2.1 浏览器直接引入

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

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

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

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

npm install --save react-router

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

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

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

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

3. 路由简单使用

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

React Router基础使用

class First extends Component {
 constructor(props) {
 super(props);
 }
 render() {
 return <p>First</p>
 }
}
class Second extends Component {
 constructor(props) {
 super(props);
 }
 render() {
 return <p>Second</p>
 }
}
class App extends Component {
 constructor(props) {
 super(props);
 }
 render() {
 return <div></div>
 }
}
render((
 <Router history={hashHistory}>
 <Route path="/" component={App} />
 <Route path="first" component={First} />
 <Route path="second" component={Second} />
 </Router>
 ),
 document.getElementById('box')
);

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

有三种:

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

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

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

let routes =
 <div>
 <Route path="/" component={App} />
 <Route path="first" component={First} />
 <Route path="second" component={Second} />
 </div>;
render(<Router routes={routes} history={hashHistory}></Router>, document.getElementById('box'));

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

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

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

class App extends Component {
 constructor(props) {
 super(props);
 }
 render() {
 return <div>{this.props.children}</div>
 }
}
render((
 <Router history={hashHistory}>
 <Route path="/" component={App}>
 <Route path="first" component={First} />
 <Route path="second" component={Second} />
 </Route>
 </Router>
 ),
 document.getElementById('box')
);

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

let routes =
 <Route path="/" component={App}>
 <Route path="first" component={First} />
 <Route path="second" component={Second} />
 </Route>;
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,推荐用来定义指向主页面的链接,当然也可以随意定义

React Router基础使用

class First extends Component {
 constructor(props) {
 super(props);
 }
 render() {
 return (
 <p>First
 <IndexLink to="/" activeStyle={{color: 'red'}}>Basic</IndexLink>
 </p>
 )
 }
}
class Second extends Component {
 constructor(props) {
 super(props);
 }
 render() {
 return <p>Second</p>
 }
}
class Basic extends Component {
 constructor(props) {
 super(props);
 }
 render() {
 return (
 <ul role="nav">
 <li><IndexLink to="/" activeStyle={{color: 'red'}}>Basic</IndexLink></li>
 <li><Link to="/first" activeStyle={{color: 'red'}}>First</Link></li>
 <li><Link to="/Second" activeClass="active">Second</Link></li>
 </ul>
 )
 }
}
class App extends Component {
 constructor(props) {
 super(props);
 }

 render() {
 return <div>
 {this.props.children}
 </div>
 }
}
render((
 <Router history={hashHistory}>
 <Route path="/" component={App}>
 <IndexRoute component={Basic} />
 <Route path="first" component={First} />
 <Route path="second" component={Second} />
 </Route>
 </Router>
 ),
 document.getElementById('box')
);
  • Redirect: 从from路径重定向到to路径
  • IndexRedirect: 在主页面,直接重定向到to路径

React Router基础使用

render((
 <Router history={hashHistory}>
 <Route path="/" component={App}>
 <IndexRoute component={Basic} />
 <IndexRedirect to="first" />
 <Redirect from="second" to="first" />
 <Route path="first" component={First} />
 <Route path="second" component={Second} />
 </Route>
 </Router>
 ),
 document.getElementById('box')
);

5. 路由的path规则

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

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

path的语法:

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

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

class First extends Component {
 constructor(props) {
 super(props);
 }
 render() {
 return (
 <p>First {this.props.params.name}
 <IndexLink to="/" activeStyle={{color: 'red'}}>Basic</IndexLink>
 </p>
 )
 }
}
.
.
<Route path="/:name" component={First} />

React Router基础使用

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

React Router基础使用

6. 路由的onEnter、onLeave钩子

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

React Router基础使用

<Route path="first" component={First} onEnter={(nextState, replace) => {
 console.log(nextState);
 alert('onEnter');
 // replace('second');
 }} onLeave={() => {
 alert('onLeave');
 }}/>

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

React Router基础使用

更多的使用参见 指南

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持三水点靠木!

Javascript 相关文章推荐
用Javascript读取中文COOKIE的解决办法
Feb 15 Javascript
javascript中的location用法简单介绍
Mar 07 Javascript
JS 强制设为首页的代码
Jan 31 Javascript
jQuery简单实现遍历数组的方法
Apr 14 Javascript
JS实现的通用表单验证插件完整实例
Aug 20 Javascript
学习javascript面向对象 javascript实现继承的方式
Jan 04 Javascript
玩转NODE.JS(四)-搭建简单的聊天室的代码
Nov 11 Javascript
vue分类筛选filter方法简单实例
Mar 30 Javascript
微信小程序 数据遍历的实现
Apr 05 Javascript
详解Vue取消eslint语法限制
Aug 04 Javascript
微信小程序云开发之使用云存储
May 17 Javascript
vue 使用async写数字动态加载效果案例
Jul 18 Javascript
JavaScript自定义分页样式
Jan 17 #Javascript
javascript实现页面滚屏效果
Jan 17 #Javascript
javascript中递归的两种写法
Jan 17 #Javascript
基本DOM节点操作
Jan 17 #Javascript
React快速入门教程
Jan 17 #Javascript
javascript操作cookie
Jan 17 #Javascript
vue.js学习笔记:如何加载本地json文件
Jan 17 #Javascript
You might like
PHP parse_url 一个好用的函数
2009/10/03 PHP
php遍历数组的4种方法总结
2014/07/05 PHP
PDO::quote讲解
2019/01/29 PHP
转一个日期输入控件,支持FF
2007/04/27 Javascript
利用javascript/jquery对上传文件格式过滤的方法
2009/07/25 Javascript
Javascript面向对象编程(二) 构造函数的继承
2011/08/28 Javascript
JavaScript 基础篇之运算符、语句(二)
2012/04/07 Javascript
jquery 实现密码框的显示与隐藏示例代码
2013/09/18 Javascript
JS中的构造函数详细解析
2014/03/10 Javascript
JS 获取浏览器和屏幕宽高等信息代码
2014/03/31 Javascript
JavaScript实现存储HTML字符串示例
2014/04/21 Javascript
javascript显示中文日期的方法
2015/06/18 Javascript
手机端转盘抽奖代码分享
2015/09/10 Javascript
javascript加载xml 并解析各节点的值(实现方法)
2016/10/12 Javascript
jQuery获取Table某列的值(推荐)
2017/03/03 Javascript
JS运动改变单物体透明度的方法分析
2018/01/23 Javascript
node.js中fs文件系统目录操作与文件信息操作
2018/02/24 Javascript
vue操作动画的记录animate.css实例代码
2019/04/26 Javascript
[46:47]2014 DOTA2国际邀请赛中国区预选赛5.21 LGD-CDEC VS NE
2014/05/22 DOTA
[03:20]2015国际邀请赛全明星表演赛
2015/08/08 DOTA
Python标准库之sqlite3使用实例
2014/11/25 Python
用Python代码来解图片迷宫的方法整理
2015/04/02 Python
Python变量和字符串详解
2017/04/29 Python
Pandas探索之高性能函数eval和query解析
2017/10/28 Python
python字符串替换re.sub()方法解析
2019/09/18 Python
CSS3 函数技巧 用css 实现js实现的事情(clac Counters Tooltip)
2017/08/15 HTML / CSS
教育科学研究生自荐信
2013/10/09 职场文书
教师演讲稿大全
2014/05/16 职场文书
农业生产宣传标语
2014/10/08 职场文书
幼儿园安全工作总结2015
2015/04/20 职场文书
民事答辩状格式范文
2015/05/21 职场文书
学生会干部任命书
2015/09/21 职场文书
学生会自荐信
2019/05/16 职场文书
基于Redis实现分布式锁的方法(lua脚本版)
2021/05/12 Redis
Pytorch中使用ImageFolder读取数据集时忽略特定文件
2022/03/23 Python
Python用tkinter实现自定义记事本的方法详解
2022/03/31 Python