zoukankan      html  css  js  c++  java
  • react-router-dom基本使用+3种传参方式

    //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
    
  • 相关阅读:
    C#4.0和VS2010新特性
    对于大型公司项目平台选择j2ee的几层认识
    移动开发
    第四讲 GridView 72般绝技
    String字符串补0或空格
    org.apache.commons.io使用实例
    BigDecimal
    JAVA String.format 方法使用介绍
    SimpleDateFormat使用详解
    java四舍五入
  • 原文地址:https://www.cnblogs.com/sgs123/p/14077680.html
Copyright © 2011-2022 走看看