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 相关文章推荐
jquery 的 $(&quot;#id&quot;).html() 无内容的解决方法
Jun 07 Javascript
UserData用法总结 lanyu出品
Jul 01 Javascript
元素的内联事件处理函数的特殊作用域在各浏览器中存在差异
Jan 12 Javascript
js判断60秒以及倒计时示例代码
Jan 24 Javascript
node.js中的emitter.on方法使用说明
Dec 10 Javascript
jQuery中:header选择器用法实例
Dec 29 Javascript
微信小程序-消息提示框实例
Nov 24 Javascript
AngularJS 霸道的过滤器小结
Apr 26 Javascript
Vue自定义指令使用方法详解
Aug 21 Javascript
angular 内存溢出的问题解决
Jul 12 Javascript
vue init webpack 建vue项目报错的解决方法
Sep 29 Javascript
ES6 迭代器与可迭代对象的实现
Feb 11 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中static静态变量的使用方法详解
2010/06/04 PHP
解析thinkphp中的M()与D()方法的区别
2013/06/22 PHP
PHP中使用hidef扩展代替define提高性能
2015/04/09 PHP
javascript实现图片自动和可控的轮播切换特效
2015/04/13 Javascript
jQuery+ajax实现实用的点赞插件代码
2016/07/06 Javascript
JavaScript生成.xls文件的代码
2016/12/22 Javascript
微信小程序如何获知用户运行小程序的场景教程
2017/05/17 Javascript
详解Node.js开发中的express-session
2017/05/19 Javascript
vue-cli配置文件——config篇
2018/01/04 Javascript
jQuery实现ajax回调函数带入参数的方法示例
2018/06/26 jQuery
微信小程序自定义音乐进度条的实例代码
2018/08/28 Javascript
ES6基础之默认参数值
2019/02/21 Javascript
vue实现滑动到底部加载更多效果
2020/10/27 Javascript
vue 修改 data 数据问题并实时显示操作
2020/09/07 Javascript
使用PYTHON创建XML文档
2012/03/01 Python
Python实现多行注释的另类方法
2014/08/22 Python
python标准算法实现数组全排列的方法
2015/03/17 Python
Python Numpy:找到list中的np.nan值方法
2018/10/30 Python
在PyCharm的 Terminal(终端)切换Python版本的方法
2019/08/02 Python
使用Python爬取弹出窗口信息的实例
2020/03/14 Python
python实现按键精灵找色点击功能教程,使用pywin32和Pillow库
2020/06/04 Python
The Hut英国:英国领先的豪华在线百货商店
2019/07/26 全球购物
瑞士最大的图书贸易公司:Orell Füssli
2019/12/28 全球购物
Deux par Deux官方网站:设计师童装
2020/01/03 全球购物
工程力学专业毕业生求职信
2013/10/06 职场文书
财务会计专业个人求职信范本
2014/01/08 职场文书
24岁生日感言
2014/01/13 职场文书
会计专业大学生求职信范文
2014/01/28 职场文书
计算机维护专业推荐信
2014/02/27 职场文书
模具专业毕业推荐信
2014/03/08 职场文书
学习经验演讲稿
2014/05/10 职场文书
小学社会实践活动总结
2014/07/03 职场文书
2019消防宣传标语!
2019/07/10 职场文书
使用nginx配置访问wgcloud的方法
2021/06/26 Servers
Pytorch中使用ImageFolder读取数据集时忽略特定文件
2022/03/23 Python
吉利入股戴姆勒后smart“长大了”
2022/04/21 数码科技