【问题标题】:react-router-dom Link onclick get the pathreact-router-dom 链接 onclick 获取路径
【发布时间】:2018-05-17 02:49:13
【问题描述】:

当我点击<Link/> 时我试图处理路径,我需要使用e.preventDefault(); 来防止路由器内部出现动画,所以这是我的代码,基本上我无法捕获更改历史目标的位置路径:

import React from 'react'; 
import { Link } from "react-router-dom";
export default class NavTransitions extends React.Component   {  
    constructor(props) {
        super(props);  
        this.changeRoutePath=this.changeRoutePath.bind(this);    
    } 
    changeRoutePath(e){
        e.preventDefault(); 
        this.props.history.push(this.match.path);
        console.log('this.match.path '+this.match.path);
        console.log('changeRoutePath');
    }
    render(){ 
        return(
            <div>
                <Link to="/item" 
                    onClick={this.changeRoutePath}>Prevent </Link>
           </div>
        );
    }
}

错误提示 this.math 未定义

【问题讨论】:

    标签: reactjs react-router react-router-dom


    【解决方案1】:

    问题是你如何访问匹配:

    this.match
    

    但应该是的

    this.props.match
    

    像这样:

    changeRoutePath(e){
            e.preventDefault(); 
            this.props.history.push(this.props.match.path);
            console.log('this.props.match.path '+ this.props.match.path);
            console.log('changeRoutePath');
        }
    

    这应该可以帮助您解决最初的问题。

    其他方法

    一个简单的方法是根本不使用链接组件,因为您只想在点击和重定向时做一些事情。所以只需使用带有 onclick 事件的简单 html 组件并将链接作为参数发送:

    <a 
        href={'#'} 
        onClick={(e) => this.changeRoutePath(e, '/item')}>
        Prevent 
    </a>
    

    以及功能:

    changeRoutePath(e, link){
        e.preventDefault();
        this.props.history.push(link);
    }
    

    您也可以将 Link 组件与箭头函数一起使用,而无需在构造函数中绑定它们:

    <Link 
        to="/item" 
        onClick={(e) => this.changeRoutePath(e)}>
        Prevent 
    </Link>
    
    changeRoutePath(e){
        e.preventDefault();
        this.props.history.push(this.props.match.path);
    }
    

    另外,记得在组件中使用 withRouter:

    import { Link, withRouter } from "react-router-dom";
    class NavTransitions extends React.Component   {  
    ...
    }
    export default withRouter(NavTransitions);
    

    React 路由器版本:

    "react-router": "^4.3.1",
    "react-router-dom": "^4.3.1",
    

    希望对你有帮助。

    【讨论】:

    • to= 放在链接标签上有什么意义,因为您只是要阻止该操作并将窗口位置推送到浏览器历史记录?
    • @KeplerIO 它默认添加到我的代码中的Link。您可以在没有 'to=' 的情况下测试它的用法,看看是否一切正常(它应该)。我知道这是多余的,因为您将覆盖“onClick”功能,好点。
    • 我明白了,如果它改变了功能,我真的很感兴趣。很难适应新图书馆中所有隐藏的魔法。
    猜你喜欢
    • 2018-03-01
    • 2021-01-09
    • 2018-11-03
    • 2017-11-12
    • 2017-12-16
    • 1970-01-01
    • 2017-01-15
    • 2020-10-03
    • 1970-01-01
    相关资源
    最近更新 更多