【问题标题】:ReactJS + React Router: How to disable link from React-Router's <Link>?ReactJS + React Router:如何从 React-Router 的 <Link> 禁用链接?
【发布时间】:2017-05-26 19:38:34
【问题描述】:

使用 React-Router 的链接,我有这样的设置:

<Link to={...}>{this.props.live? "Live": "Not Live"}</Link>

如果this.props.live 被传入,我想简单地显示一个文本“Live”,它将指向一个新页面。如果this.props.live 没有传入,想要显示文本“Not Live”但从中删除超链接/停用/禁用它。

有可能吗?我试过&lt;div style={{pointerEvents: "none"}}&gt;Not Live&lt;/div&gt;,但不起作用。

将投票并接受答案。谢谢!

【问题讨论】:

    标签: javascript html css reactjs react-router


    【解决方案1】:

    你应该这样做:

    let component;
    
    component=this.props.live? <Link to={...}> Live </Link>: <div> Not Live </div>
     render() {
        {component}
      }
    

    干杯:)

    【讨论】:

    • 我怎么没看到。叹。谢谢!
    • 最好将displayLinkOrNot重命名为component,因为displayLinkOrNot应该存储一个布尔值。为实际上将包含 ui 的变量选择错误的名称。
    • 感谢您的建议 :)
    【解决方案2】:
    this.props.live
    ? <Link to={...}> Live </Link>
    : <div> Not Live </div>
    

    【讨论】:

      【解决方案3】:

      您可以使用evt.preventDefault()防止页面被重定向

      class MyComponent extends React.Component {
        constructor(props) {
          this.handleLinkClick = this.handleLinkClick.bind(this);
        }
        handleLinkClick(evt) {
          if (!this.props.live) {
            evt.preventDefault(); // will prevent redirection
          }
        }
        render() {
          <Link onClick={this.handleLinkClick} to={...}>
            {this.props.live? "Live": "Not Live"}
          </Link>
        }
      }
      

      简写但controversial版本

      <Link onClick={evt => !this.props.live && evt.preventDefault()} to={...}>
        {this.props.live? "Live": "Not Live"}
      </Link>
      

      API docs

      【讨论】:

        猜你喜欢
        • 2020-07-04
        • 2021-09-27
        • 2021-02-21
        • 2019-08-15
        • 2017-03-15
        • 2017-10-14
        • 1970-01-01
        • 2017-08-12
        相关资源
        最近更新 更多