react路由-属性2

请先查看第一篇

https://blog.youkuaiyun.com/oracle8090/article/details/112368060

1.实现使用按钮跳转路由 

    this.props.history.push("/cart")

    this.props.history.replace("/cart")

    push和replace的区别:push添加,replace是替换页面,主要体现,是否可以回退

在原有项目的基础上增加Cart 页面

import React from 'react'
import Nav from '../Nav'

export default class Cart extends React.Component{
    render(){
        return(
            <div>
                <Nav/>
                Cart
            </div>
        )
    }

}

添加Nav链接 

 

在app.js页面添加路由

修改home页面 

实现用按钮跳转 

2.、路由的作用域

    被路由直接管理的对象,存在history,否则则不存在,解决方案:可以传递history

    <Computer history={ this.props.history }/>

    this.props.history.push("/");

  如添加

import React from 'react'


export default class Computer extends React.Component{
    clickHandle=()=>{
        this.props.history.push("/")
    }
  
    render(){
        return(
            <div>
                 <button onClick={this.clickHandle}>去首页</button>
            </div>
        )
    }

}

在cart中引用 

不要在Nav/index 和 App.js中配置  

点击去首页会报错

原因是只有被路由管理的页面才有history 需要做以下修改

3.基于第二步的修改  使用高级组件 

创建Game页面

import React from 'react'
import {withRouter} from 'react-router-dom'
class Game extends React.Component{
    clickHandle=()=>{
        this.props.history.push("/")
    }
  
    render(){
        return(
            <div>
                 <button onClick={this.clickHandle}>game 去首页</button>
            </div>
        )
    }

}

//高级组件
export default withRouter(Game)

在 computer中直接引用game,不需要传递history就可以直接进行路由的跳转

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值