简体   繁体   English

react-router:如何禁用<link> ,如果它是活跃的?

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

How can I disable a <Link> in react-router, if its URL already active?我如何禁用 react-router 中的<Link> ,如果它的 URL 已经激活? Eg if my URL wouldn't change on a click on <Link> I want to prevent clicking at all or render a <span> instead of a <Link> .例如,如果我的 URL 在单击<Link>时不会改变,我想完全阻止单击或呈现<span>而不是<Link>

The only solution which comes to my mind is using activeClassName (or activeStyle ) and setting pointer-events: none;我想到的唯一解决方案是使用activeClassName (或activeStyle )并设置pointer-events: none; , but I'd rather like to use a solution which works in IE9 and IE10. ,但我宁愿使用适用于 IE9 和 IE10 的解决方案。

You can use CSS's pointer-events attribute.您可以使用 CSS 的pointer-events属性。 This will work with most of the browsers.这将适用于大多数浏览器。 For example your JS code:例如你的JS代码:

class Foo extends React.Component {
  render() {
    return (
      <Link to='/bar' className='disabled-link'>Bar</Link>
    );
  }
}

and CSS:和 CSS:

.disabled-link {
  pointer-events: none;
}

Links:链接:

The How to disable HTML links answer attached suggested using both disabled and pointer-events: none for maximum browser-support.附加的如何禁用 HTML 链接答案建议同时使用disabledpointer-events: none以获得最大的浏览器支持。

a[disabled] {
    pointer-events: none;
}

Link to source: How to disable Link链接到源:如何禁用链接

I'm not going to ask why you would want this behavior, but I guess you can wrap <Link /> in your own custom link component.我不会问您为什么想要这种行为,但我想您可以将<Link />包装在您自己的自定义链接组件中。

<MyLink to="/foo/bar" linktext="Maybe a link maybe a span" route={this.props.route} />

class MyLink extends Component {
    render () {
        if(this.props.route === this.props.to){
            return <span>{this.props.linktext}</span>
        }
        return <Link to={this.props.to}>{this.props.linktext}</Link>
    }
}

(ES6, but you probably get the general idea...) (ES6,但您可能已经大致了解了...)

这对我有用:

<Link to={isActive ? '/link-to-route' : '#'} />

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 .这是一个适用于 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 <Link onClick={this.onClick.bind(this)} {...other}>{children}</Link>
    }
}

export default withRouter(SafeLink);

You can then use your link as (any extra props from Link would work):然后您可以将您的链接用作(来自Link任何额外道具都可以使用):

<SafeLink className="some_class" to="/some_route">Link text</SafeLink>

All the goodness of React Router NavLink with the disable ability.具有禁用功能的React Router NavLink 的所有优点。

import React from "react"; // v16.3.2
import { withRouter, NavLink } from "react-router-dom"; // v4.2.2

export const Link = withRouter(function Link(props) {
  const { children, history, to, staticContext, ...rest } = props;
  return <>
    {history.location.pathname === to ?
      <span>{children}</span>
      :
      <NavLink {...{to, ...rest}}>{children}</NavLink>
    }
  </>
});

React Router's Route component has three different ways to render content based on the current route. React Router 的Route组件具有三种不同的方式来基于当前路由呈现内容。 While component is most typically used to show a component only during a match, the children component takes in a ({match}) => {return <stuff/>} callback that can render things cased on match even when the routes don't match .虽然component最常用于仅在匹配期间显示组件,但children组件接受({match}) => {return <stuff/>}回调,即使路由不匹配,它也可以呈现匹配的内容匹配

I've created a NavLink class that replaces a Link with a span and adds a class when its to route is active.我创建了一个 NavLink 类,它用一个跨度替换一个链接,并在它to路由处于活动状态时添加一个类。

class NavLink extends Component {
  render() {
    var { className, activeClassName, to, exact, ...rest } = this.props;
    return(
      <Route
        path={to}
        exact={exact}
        children={({ match }) => {
          if (match) {
            return <span className={className + " " + activeClassName}>{this.props.children}</span>;
          } else {
            return <Link className={className} to={to} {...rest}/>;
          }
        }}
      />
    );
  }
}

Then create a navlink like so然后像这样创建一个导航链接

<NavLink to="/dashboard" className="navlink" activeClassName="active">

React Router's NavLink does something similar, but that still allows the user to click into the link and push history. React Router 的 NavLink做了类似的事情,但它仍然允许用户点击链接并推送历史记录。

Based on nbeuchat's answer and component - I've created an own improved version of component that overrides react router's Link component for my project.基于 nbeuchat 的答案和组件 - 我创建了一个自己的改进版本的组件,它覆盖了我的项目的react router's Link组件。

In my case I had to allow passing an object to to prop (as native react-router-dom link does), also I've added a checking of search query and hash along with the pathname在我的情况下,我必须允许将对象传递to prop(如本机react-router-dom链接所做的那样),我还添加了对search queryhash以及pathname

import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { Link as ReactLink } from 'react-router-dom';
import { withRouter } from "react-router";

const propTypes = {
  to: PropTypes.oneOfType([PropTypes.string, PropTypes.func, PropTypes.object]),
  location: PropTypes.object,
  children: PropTypes.node,
  onClick: PropTypes.func,
  disabled: PropTypes.bool,
  staticContext: PropTypes.object
};

class Link extends Component {
  handleClick = (event) => {
    if (this.props.disabled) {
      event.preventDefault();
    }

    if (typeof this.props.to === 'object') {
      let {
        pathname,
        search = '',
        hash = ''
      } = this.props.to;
      let { location } = this.props;

      // Prepend with ? to match props.location.search
      if (search[0] !== '?') {
        search = '?' + search;
      }

      if (
        pathname === location.pathname
        && search === location.search
        && hash === location.hash
      ) {
        event.preventDefault();
      }
    } else {
      let { to, location } = this.props;

      if (to === location.pathname + location.search + location.hash) {
        event.preventDefault();
      }
    }

    // Ensure that if we passed another onClick method as props, it will be called too
    if (this.props.onClick) {
      this.props.onClick(event);
    }
  };

  render() {
    let { onClick, children, staticContext, ...restProps } = this.props;
    return (
      <ReactLink
        onClick={ this.handleClick }
        { ...restProps }
      >
        { children }
      </ReactLink>
    );
  }
}

Link.propTypes = propTypes;

export default withRouter(Link);

Another option to solve this problem would be to use a ConditionalWrapper component which renders the <Link> tag based on a condition.解决此问题的另一种选择是使用ConditionalWrapper组件,该组件根据条件呈现<Link>标记。

This is the ConditionalWrapper component which I used based on this blog here https://blog.hackages.io/conditionally-wrap-an-element-in-react-a8b9a47fab2 :这是我基于此博客使用的ConditionalWrapper组件https://blog.hackages.io/conditionally-wrap-an-element-in-react-a8b9a47fab2

const ConditionalWrapper = ({ condition, wrapper, children }) =>
    condition ? wrapper(children) : children;

export default ConditionalWrapper

This is how we have used it:这就是我们使用它的方式:

const SearchButton = () => {
    const {
        searchData,
    } = useContext(SearchContext)

    const isValid = () => searchData?.search.length > 2

    return (<ConditionalWrapper condition={isValid()}
                                wrapper={children => <Link href={buildUrl(searchData)}>{children}</Link>}>
            <a
                className={`ml-auto bg-${isValid()
                    ? 'primary'
                    : 'secondary'} text-white font-filosofia italic text-lg md:text-2xl px-4 md:px-8 pb-1.5`}>{t(
                    'search')}</a>
        </ConditionalWrapper>
    )
}

This solution does not render the Link element and avoids also code duplication.此解决方案不呈现Link元素,也避免了代码重复。

... const [isActive, setIsActive] = useState(true); ... const [isActive, setIsActive] = useState(true); ... ...

you can try this, this worked for me.你可以试试这个,这对我有用。

I think you should you atrribute to=null to set disable a link.我认为您应该将 atrtribute to=null设置为禁用链接。

See an example at here https://stackoverflow.com/a/44709182/4787879在此处查看示例https://stackoverflow.com/a/44709182/4787879

如果它适合你的设计,在它上面放一个 div,然后操作 z-index。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM