react-router-dom 链接 onclick 获取路径

Leo*_*014 1 reactjs react-router react-router-dom

我在单击时尝试处理路径<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>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

错误说 this.math 是未定义的

c-c*_*vez 5

问题是您如何访问匹配项:

this.match
Run Code Online (Sandbox Code Playgroud)

但应该是

this.props.match
Run Code Online (Sandbox Code Playgroud)

像这样:

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');
    }
Run Code Online (Sandbox Code Playgroud)

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

其他方法

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

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

和功能:

changeRoutePath(e, link){
    e.preventDefault();
    this.props.history.push(link);
}
Run Code Online (Sandbox Code Playgroud)

您还可以使用带有箭头函数的 Link 组件,而无需在构造函数中绑定它们:

<Link 
    to="/item" 
    onClick={(e) => this.changeRoutePath(e)}>
    Prevent 
</Link>

changeRoutePath(e){
    e.preventDefault();
    this.props.history.push(this.props.match.path);
}
Run Code Online (Sandbox Code Playgroud)

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

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

反应路由器版本:

"react-router": "^4.3.1",
"react-router-dom": "^4.3.1",
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你。