React 路由&脚手架

1.创建react项目

  npm install -g create-react-app 全局环境 

 

  create-react-app my-app 创建项目 

 

 cd my-app 进入项目 

 

  npm start 启动 

React-router介绍

什么是路由?

        路由是根据不同的 url 地址展示不同的内容或页面。

React Router

        一个针对React而设计的路由解决方案、可以友好的帮你解决React components URl之间的同步映射关系。

安装低版本react-router

卸载高版本react react-dom

 npm uninstall react react-dom --save-dev 

安装react-router2.0版本 安装axios

 npm i react@15 react-dom@15 react-router@2 axios --save-dev 

 

2.准备React组件

 import React from 'react'

 

import ReactDOM from 'react-dom’

 

import { Router, Route, Link, hashHistory} from ‘react-router’

 

//react-router中定义了history这个属性 用于方便管理路由的方向

 

//browserHistory/ hashHistory 

3.link

定义链接的组件,类似于a标签。

 

 <Link to=“/users>users</Link> {this.props.children} //==相当于路由试图的容器 

4.定义路由 index.js

 1 render (<Router history={hashHistory}>
 2 
 3 <Route path=”/" component={Demo}>
 4 
 5 <Route path="/home" component={Header}></Route>
 6 
 7 <Route path="/about" component={Con}></Route>
 8 
 9 </Route>
10 
11 </Router>, document.getElementById('root'))

 

<Route>组件有如下属性:

pathstring: 路由匹配路径。(没有path属性的Route 总是会 匹配);

 

Component==设置该路径要加载的组件

索引 IndexRoute

指定默认情况下加载的子组件。你可以把IndexRoute想象成某个路径的index.html。

 

例如:

 1 <Route path="/" component={App}> <IndexRoute component={Index}/> </Route> 

样式

当路径匹配时会触发activeStyle属性。

 

 1 const ACTIVE = { color: 'red' }  

普通链接

 1 <Link to="/users" activeStyle={ACTIVE}>users</Link> 

地址栏传参

定义:

 1 <Link to=“/users/1>users</Link> <Route path="/user/:xxxx" component={User}/> 

取得参数:

1 this.props.params.xxxx==1 

路径跳转(编程式路由)

在事件中进行路由路径跳转

 1 hashHistory.push('/home')  

绝对路径和重定向

相对路径:

不以/开头的路径,匹配时就会相对于父组件的路径。

 1 <Route path="inbox" component={Inbox}> <Route path="messages/:id" component={Message} /> </Route> 

访问路径:/inbox/messages/:id

 

绝对路径:

/开头的路径。如果在嵌套路由中使用会跳出父组件的影响。

 1 <Route path="inbox" component={Inbox}> <Route path=“/messages/:id" component={Message} /> </Route> 

 

访问路径:/messages/:id

 

重定向:

当路径匹配from的时候,自动重定向(跳转)to的地址上面。

 

 1 <Route path=”/index" component={index}> <Redirect from=”/index/a" to=“/other" /> </Route> 

 

/index/a 跳转到 /other

 

 

重定向

 1 <IndexRedirect to="/home"/> 

 

查询符-query

定义:

 1 <Route path="/user/:xxxx" component={User}/> 

 

取得参数:

 1 this.props.params.xxxx 

例如:

 1 <Link to={{pathname:'/list',query:{id:item.goodsID} }}> <Route path="/user" component={User}/> url:/user/10086?foo=bar 

 

this.props.params.userId 10086

this.props.location.query.foo bar

 

总结:

路由的各个组件的生命周期和普通的组件生命周期是一样的。路由根据不同的url来加载和卸载不同的组件

转载于:https://www.cnblogs.com/fandaye/p/11477543.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值