zoukankan      html  css  js  c++  java
  • 在React中使用react-router-dom路由

    在a标签下面添加一个按钮并加上onClick事件,通过this.props.history.push这个函数跳转到detail页面。在路由组件中加入的代码就是将history这个对象注册到组件的props中去,然后就可以在子组件中通过props调用history的push方法跳转页面。

    很多场景下,我们还需要在页面跳转的同时传递参数,在react-router-dom中,同样提供了两种方式进行传参。

     

    隐式传参

    此外还可以通过push函数隐式传参。

    修改home.js代码如下:

    在detail.js中,就可以使用this.props.history.location.state获取home传过来的参数:

    componentDidMount() {
        //console.log(this.props.match.params);
        console.log(this.props.history.location.state);
    }
    

    跳转后打开控制台可以看到参数被打印:

    其他函数

    replace

    有些场景下,重复使用push或a标签跳转会产生死循环,为了避免这种情况出现,react-router-dom提供了replace。在可能会出现死循环的地方使用replace来跳转:

    this.props.history.replace('/detail');
    

    goBack

    场景中需要返回上级页面的时候使用:

    this.props.history.goBack();


  • 相关阅读:
    position之属性
    Grid网格布局
    position 属性指定了元素的定位类型
    注册表单
    简单页面
    自我介绍
    正则表达式
    Dom和Bom
    颜色和单位
    伪类和伪元素的区别
  • 原文地址:https://www.cnblogs.com/yangjingyang/p/11574835.html
Copyright © 2011-2022 走看看