查看: 97|回覆: 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.

在本版发帖返回顶部