react-router-dom Link onclick 获取路径

react-router-dom Link onclick get the path

我在单击 <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 未定义

问题在于您如何访问匹配项:

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');
    }

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

其他方法

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

<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",

希望对您有所帮助。