查看: 83|回复: 0

react-router-dom基本使用+3种传参方式

[复制链接]

0

主题

0

回帖

0

积分

热心网友

金币
0
阅读权限
220
精华
0
威望
0
贡献
0
在线时间
0 小时
注册时间
2010-4-21
发表于 2020-12-3 09:15:00 | 显示全部楼层 |阅读模式
//App.js
import { 
  BrowserRouter as Router,
  Route,
  Link,
} from "react-router-dom";
// 引入组件
import Home from "....";
import News from "...."
function App() {
  return (
    <Router>
      <Link to="/">首页</Link>
      <Link to="/news">新闻</Link>
      <Route exact path="/" component={Home} />
      <Route path="/news" component={News} />   
    </Router>
  );
}
export defautl App;

如何传递参数(3种)

1、params传参(动态路由)

特点:刷新页面参数不消失,参数会在地址栏显示

  • 路由配置
<Route path='/about/:id' component={About} />
  • 跳转方式
  //传递参数可以拆分为对象写法:{pathname:'/about/3'}
  //html:
  <Link to={'/about/3'}>点击跳转</Link>
  //js:
  this.props.history.push('/about/3')
  • 获取值
this.props.match.params.id  // 3

2、query传参

特点:刷新页面参数消失,参数不会在地址栏显示

  • 路由配置
<Route path='/about' component={About} />
  • 跳转方式
  //html:
  <Link to={{pathname:'/about', query:{id:3}}}>点击跳转</Link>
  //js:
  this.props.history.push({pathname:'/about', query:{id:3}})
  • 获取值
this.props.location.query.id  // 3

3、state传参

特点:刷新页面参数不消失,参数不会在地址栏显示

  • 路由配置
<Route path='/about' component={About} />
  • 跳转方式
  //html:
  <Link to={{pathname:'/about', state:{id:3}}}>点击跳转</Link>
  //js:
  this.props.history.push({pathname:'/about', state:{id:3}})
  • 获取值
this.props.location.state.id  // 3


来源:https://www.cnblogs.com/sgs123/p/14077680.html
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

相关侵权、举报、投诉及建议等,请发 E-mail:qiongdian@foxmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部