React路由跳转和传参

React,Link路由的跳转和传参

1. 安装react-router-dom
npm install react-router-dom
2. 在项目中使用react-router-dom
  • 首先在入口文件引入这个模块
// 这里有BrowserRouter (历史记录) 和 HashRouter(hash) 两种模式
import { BrowserRouter as Router} from 'react-router-dom'
  • 然后用<Router>把渲染的根节点包裹起来
ReactDOM.render(<Router><App /></Router>, document.getElementById('root'));
3. 接下来在组件中就可以使用路由跳转了
  • 在需要使用路由跳转的页面引入下面几个常用组件(可根据需要引入)
import {Route, NavLink, Switch, Redirect} from 'react-router-dom'
  • 定义几个点击跳转的按钮,<NavLink>自带有active的class类名
<NavLink to="/one">页面1</NavLink> // 最终渲染成 a标签
<NavLink to="/two">页面2</NavLink>
<NavLink to="/three">页面3</NavLink>
<NavLink to="/four">页面4</NavLink>
  • 在定义几个路由跳转显示的组件<Route>
<Switch> // 使用Switch, 作用是多个Route匹配,只渲染找到的第一个
	<Route path="/one" component={One}/>
	<Route path="/two" component={Two}/> // 一个坑
	<Route path="/three" component={Three}/>
	<Route path="/four" component={Four}/>
	<Redirect from="/" to="/one" exact/> // Redirect 重定向,默认显示one组件, exact属性是精确匹配前面from属性的值
	<Route component={NotFound}/> //所有的都不匹配就显示404页面
</Switch>
  • 子路由定义, 比如two组件中定义子路由.
// 这里注意父路由不能写 exact 属性
<NavLink to="/two/a">子路由a</NavLink>
<NavLink to="/two/b">子路由b</NavLink>
<Switch>
  <Route path="/two/a" component={TwoA}></Route>
  <Route path="/two/b" component={TwoB}></Route>
  <Redirect from="/two" to="/two/a" exact></Redirect>
</Switch>
4.传递参数
  • Params
<Route path='/path/:name' component={Path}/> // name是形参
<NavLink to="/path/2">跳转传参</NavLink> // 2是传递的实参
this.props.history.push({pathname:"/path/" + name}); // 编程式跳转传参
读取参数用:this.props.match.params.name // 跳转成功后拿到参数
  • query
<Route path='/query' component={Query}/>
<NavLink to={{ path :'/query', query:{name:'sunny'}}}>跳转传参</NavLink>
this.props.history.push({pathname:"/query",query:{name:'sunny'}}); // 编程式跳转
读取参数用: this.props.location.query.name
  • state
<Route path='/sort' component={Sort}/>
<NavLink to={{path:'/sort ', state:{name :'sunny' }}}>跳转传参</NavLink> 
this.props.history.push({pathname:"/sort ",state:{name:'sunny'}}); // 编程式跳转
读取参数用: this.props.location.query.state 
  • search
<Route path='/web/departManange ' component={DepartManange}/>
<NavLink to="web/departManange?tenantId=12121212">跳转传参</NavLink>
this.props.history.push({pathname:"/web/departManange?tenantId" + row.tenantId});
读取参数用: this.props.location.search
  • 注意 query state 和 search 传递的参数刷新页面后参数丢失!
  • 最后 逆战 小白变大白!!!
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值