react-router: How to disable a <Link>, if its active?

后端 未结 9 1009
谎友^
谎友^ 2020-12-14 06:10

How can I disable a in react-router, if its URL already active? E.g. if my URL wouldn\'t change on a click on I want to p

9条回答
  •  抹茶落季
    2020-12-14 06:33

    Another possibility is to disable the click event if clicking already on the same path. Here is a solution that works with react-router v4.

    import React, { Component } from 'react';
    import { Link, withRouter } from 'react-router-dom';
    
    class SafeLink extends Component {
        onClick(event){
            if(this.props.to === this.props.history.location.pathname){
                event.preventDefault();
            }
    
            // Ensure that if we passed another onClick method as props, it will be called too
            if(this.props.onClick){
                this.props.onClick();
            }
        }
    
        render() {
            const { children, onClick, ...other } = this.props;
            return {children}
        }
    }
    
    export default withRouter(SafeLink);
    

    You can then use your link as (any extra props from Link would work):

    Link text
    

提交回复
热议问题