如何在React中禁用链接?

15

我在我的ReactJS应用程序中有这个:

import Link from 'react-router/lib/Link'

一直试图禁用这个链接,但是没有达到预期的效果:

<Link disable={true}/>

它只是将其渲染为不可见状态。我如何在符合条件时禁用ReactJS中的Link?

4个回答

23

关于 react-router 中存在的许多问题,Link组件不支持disabled属性。若要解决此问题,可以尝试以下方法:issue

1. onClick事件

使用preventDefault()来处理onClick事件。

/* YourComponent.js */
class YourComponent extends React.Component {
  render() {
    return (
      <Link onClick={e => e.preventDefault()} />
    );
  }
}

2. CSS的pointer-events属性

/* YourComponent.js */
class YourComponent extends React.Component {
  render() {
    return (
      <Link className='disabled-link' />
    );
  }
}

/* css file */
.disable-link {
  pointer-events: none;
}

或者您可以使用 内联 样式

/* YourComponent.js */
class YourComponent extends React.Component {
  render() {
    return (
      <Link style={{ pointerEvents: 'none' }} />
    );
  }
}

我使用的是方法2,在我的项目中更加清晰明了。


pointer-events: none 设置为不好的解决方案,因为您仍然可以使用键盘访问链接。 您还需要设置 tabIndex 以防止这种情况发生。 - Spikatrix

1
另一种选择是让函数根据某些条件返回2个不同的链接...
const fnSomePath = () =>{
return somecondition ? `www.abc.xyz` : `#`
}

然后调用包含你的链接的函数:

<ListGroupItem>
  <NavLink to={{pathname: fnSomePath()}}>
      TEXT
   </NavLInk>
</ListGroupItem>


0

您可以根据某些状态有条件地渲染类似于禁用链接的内容。

例如,在 TypeScript 中:

export interface Location {
  pathname: string; 
  search: string;
  state: any;
  hash: string;
  key ?: string;
}
interface LinkProps {
  to: string | Location
  replace?:boolean
}
interface DisableLinkProps extends LinkProps {
  enabled: boolean
  linkText:string
}
export class DisableLink extends React.Component<DisableLinkProps, undefined> {
  render() {
    var element= this.props.enabled ? <span className="disableLinkDisabled">{this.props.linkText}</span> : <Link to={this.props.to} replace={this.props.replace}>{this.props.linkText}</Link>
    return element;
  }
}

interface DemoClassState {
  linkEnabled:boolean
}
export class DemoClass extends React.Component<undefined, DemoClassState> {
  constructor(props) {
    super(props);
    this.state = { linkEnabled:false }
  }
  toggleLinkEnabled = () => {
    this.setState((prevState) => {
        return {
            linkEnabled: !prevState.linkEnabled
        }
    });
  }
  render() {
    return <div>
        <DisableLink enabled={this.state.linkEnabled} to="/somewhere" linkText="Some link" />
        <button onClick={this.toggleLinkEnabled}>Toggle link enabled</button>
        </div>
  }
}

0

这实际上有点棘手。甚至可能有些不明智。

https://css-tricks.com/how-to-disable-links/

我所采取的方式(不是故意的)是不渲染该链接。
我从react-router的组件中编写了一个新组件。
import React from 'react';
import { Link } from 'react-router-dom';

export default function ToggleableLink(props)  {
    const { disabled, ...rest } = props;
    return disabled ? props.children : <Link {...rest}>{props.children}</Link>;
}

使用方法:

<ToggleableLink disabled={!showTheLink}>Foobar</ToggleableLink>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接