react路由react-router5的配置

1.下载安装react路由

cnpm i react-router-dom@5 -S

2. 创建1个router.js文件配置路由

import {  BrowserRouter , HashRouter , Route , Link , NavLink} from 'react-router-dom'

class App extends Component {
  render() {
    return (
      <BrowserRouter>
          <Route path='/' exact component={Home}></Route>
      </BrowserRouter>
    )
  }
}                             // history模式

class App extends Component {
  render() {
    return (
      <HashRouter>
          <Route path='/' exact component={Home}></Route>
      </HashRouter>
    )
  }
}                     //hash模式

3.路由api说明

Route: 用来控制路径对应显示的组件

path:指定路由跳转路径
exact: 精确匹配路由
component:路由对应的组件

switch:解决route的唯一渲染,它是为了保证路由只渲染一个路径。没有switch会渲染path上所有的组件

<Switch>
            <Route path="/home" component={Home} />

</Switch>

路由跳转组件Link 

<Link to={{

pathname: '/home',       //路径

search: '?name=cedric',  //参数

hash: '#Hash',   //放入路径的 hash值

state:{ fromWechat:true }}} //状态持续到 location可用于统计页面来源 this.props.location.state可见

> </Link>

路由跳转组件NavLink可添加高亮效果

<NavLink to="/home" activeStyle={{ fontWeight: 'bold', color: 'red' }} >  </NavLink>

路由重定向组件Redirect

<Switch> <Route path='/home' exact component={Home}></Route> <Route path='/login' exact component={Login}></Route> <Redirect to="/home" from='/' exact /> </Switch>

 withRouter将一个非路由组件包裹为路由组件,使这个非路由组件也能访问到当前路由的match, location, history对象

编程式导航 - history 对象

this.props.history.push('/home')

   写在点击事件里可实现跳转

只有通过 Route 组件渲染的组件,才能在 this.props 上找到 history 对象

路由传参

params 参数

路由链接(携带参数):<Link to='/demo/test/tom/18'}>详情</Link>
注册路由(声明接收):<Route path="/demo/test/:name/:age" component={Test}/>
接收参数:this.props.match.params
search 参数
路由链接(携带参数):<Link to='/demo/test?name=tom&age=18'}>详情</Link>
注册路由(无需声明,正常注册即可):<Route path="/demo/test" component={Test}/>
接收参数:this.props.location.search

state参数

路由链接(携带参数):<Link to={{pathname:'/demo/test',state:{name:'tom',age:18}}}>详情</Link>
注册路由(无需声明,正常注册即可):<Route path="/demo/test" component={Test}/>
接收参数:this.props.location.state

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值