react-router-dome的使用二

点击切换路由

修改引入方式变成非Hash模式

import {BrowserRouter as Router,Route,Switch,Redirect} from  "react-router-dom"

1:在Home.js中

改写代码加一个a标签 测试代码的跳转 通过a标签

import React, { Component } from 'react'

export default class Home extends Component {
    render() {
        console.log(this.props);
        return (
            <div>
                我是首页
                <a href="/mine">去个人页面</a>
            </div>
        )
    }
}

2:点击跳转 代码如下 声明一个按钮 给按钮绑定点击事件

goToMine=()=>{
        this.props.history.push("/mine");
    }
    render() {

    console.log(this.props);
        return (
            <div>
                我是首页
                <a href="/mine">去个人页面</a>
                <button onClick={()=>this.goToMine()}>点击事件的跳转</button>
            </div>
        )

    }

很多时候 我们可以通过this.props将路由传递的信息 全部进行输出 方便研究

 

3:带参数的处理

<Switch>        
        <Route path="/center" component={Center} excat></Route>
        <Route path="/mine" component={Mine} excat>
        </Route>
        <Route path="/order/:id" component={Order} exact></Route> 
        <Route path="/" component={Home} exact>       
        </Route>
        </Switch>

 

4:访问的地方

<ul>
            <li><a href="/order/5">我的订单</a></li>
        </ul>

5:在view中可以接收到参数

import React, { Component } from 'react'

export default class Order extends Component {
    render() {
        // console.log(this.props);
        return (
            <div>
                我的订单信息{this.props.match.params.id}
            </div>
        )
    }
}

6:也可以手动的隐式传参

   <button onClick={()=>{this.props.history.push({
                pathname:"/order",
                state:{
                    id:1111
                }
            })}}>点击跳转</button>

7:接收方法的改变

return (
            <div>
            
                {/* 我的订单信息{this.props.match.params.id} */}
            {/*点击过来的参数为*/} 
{this.props.history.location.state.id}
            </div>

8:还需要修改路由的地方 把后面的/:id去除掉

<Route path="/order" component={Order} excat></Route> 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值