实战 React 第2天:掌握 react-router-dom 路由配置、跳转与传参
2019-06-04 15:02
731 查看
版权声明:本文为回眸一笑原创作品,欢迎关注「前端集锦」公众号。 https://blog.csdn.net/weixin_44135121/article/details/90767640
react-router-dom 路由配置、跳转与传参
本文所述的 react-router-dom 版本为 5.0.0;react-router 版本为 5.0.0。
一、react-router-dom 路由配置
import React from 'react'; import {HashRouter, BrowserRouter,Route,Redirect,Switch,Link,NavLink} from 'react-router-dom'; import Home from './component/home'; import Detail from './component/detail'; const Router = () => ( <BrowserRouter> <Route exact path="/" component={Home}/> <Route path="/detail" name="detail" component={Detail}/> </BrowserRouter> ); export default Router;
- 路由配置属性主要有 path、name、component 等。
path:组件相对路径
name:组件路径别名
component:组件地址 - 在路由配置中,有两个属性 exact 和 strict 表示路径匹配。
“/detail” exact 属性为 true 时匹配的路由有:"/detail/",
但是 url 中有 “/detail/” 匹配不到。
“/detail” strict 属性为 true 时匹配的路由有:"/detail",
但是 “/detail/” 可以被匹配到。
综上所述,要想严格匹配,就需要将 exact 和 strict 都设为 true
二、react-router-dom 路由跳转
路由跳转有两种方式。
- link 或者 NavLink形式,实质是个 a 标签。区别是后者可以切换时改变样式,用法如下:
<ul> <li><NavLink exact to="/" activeStyle={{ fontWeight: 'bold', color: 'red' }}>home</NavLink> </li> <li><NavLink exact to="/detail" activeStyle={{ fontWeight: 'bold', color: 'red' }}>detail</NavLink> </li> </ul>
- 直接使用点击事件,用法如下:
<ul> <li onClick={() => this.props.history.push({pathname:'detail'})}><div>home</div> </li> <li onClick={() => this.props.history.push({pathname:'home'})}><div>detail</div> </li> </ul>
三、react-router-dom 路由传参
上面有提到两种路由跳转方式,相应的路由传参也有两种方式。
- 组件跳转传参
<ul> <li><NavLink exact to="/" activeStyle={{ fontWeight: 'bold', color: 'red' }}>home</NavLink> </li> <li><NavLink exact to={{pathname:'detail',state:{id:2}}} activeStyle={{ fontWeight: 'bold', color: 'red' }}>detail</NavLink> </li> </ul>
使用 NavLink 进行配置,使用 to 属性进行跳转和传参。
- 事件跳转传参
<ul> <li onClick={() => this.props.history.push({pathname:'detail',state:{id:1}})}><div>home</div> </li> <li onClick={() => this.props.history.push({pathname:'home',state:{ id:0}})}><div>detail</div> </li> </ul>
- 获取参数
constructor(props){ super(props); console.log(this.props.history.location.state); }
相关文章推荐
- 关于react-router4中路由的配置,传参,跳转,可选参数写法
- 使用react-router-dom优雅的实现页面(路由)跳转, 而且保持当前页面状态
- react路由的使用方法以及通过路由如何传参传递私有属性--【基于最新版本的react-router-dom(4.2.2)】
- react-router HashRouter和BrowserHistory的区别, 以及配置、使用, Link跳转传参等等
- react-router-dom示例讲解(十)——路由配置
- 阿里飞冰使用Link路由跳转报错之“react-router”与“react-router-dom”
- react-router-dom 手动控制路由跳转
- react-router-dom 函数跳转传参
- React PureComponent导致react-router-dom Link 失效 路由跳转失败(地址栏变,页面不跳转)
- 试着用React写项目-利用react-router解决跳转路由等问题(三)
- React的react-router4的路由配置
- 试着用React写项目-利用react-router解决跳转路由等问题(三)
- react-router v4 使用 history 控制路由跳转
- React-router(5)params 路由传参
- react项目引入路由组件react-router-dom
- React第三方组件1(路由管理之Router的使用③传参)
- react-router JS 控制路由跳转实例
- react-router 4.2.0<link>页面跳转-传参与不传参
- 试着用React写项目-利用react-router解决跳转路由等问题(一)
- react-router JS 控制路由跳转(转载)