【问题标题】:How to create a link in React component with onClick handler?如何使用 onClick 处理程序在 React 组件中创建链接?
【发布时间】:2016-08-07 02:53:19
【问题描述】:

在没有URL 的情况下,如何使用 onClick 回调函数创建链接的正确/标准方法是什么?

<a href="#" onClick={this.handleClick}>click me!</a>

或者没有href,但是链接在视觉上是不可点击的:

<a onClick={this.handleClick}>click me!</a>

我读过的所有教程都使用 &lt;a&gt; 以外的其他元素 - 可点击 &lt;span&gt;&lt;div&gt; 等,但我想使用 &lt;a&gt;

【问题讨论】:

  • 取决于您希望链接的位置。如果它用于内部应用导航,那么路由库可能会有一个 &lt;Link&gt; 组件为您执行此操作,否则您将不得不使用 css 将其设置为像链接一样的样式。但我再次建议制作一个独立组件来执行此操作。

标签: javascript reactjs components


【解决方案1】:

对于REACT中的锚标签,如果我们想在不改变URL的情况下使用onClick,那么可以使用如下

<a
    style={{ cursor:"pointer" }}
    href={null}
    onClick={() =>
                  this.toggleModal("Rental Objects With Current Rent")
                }
 >
Click Me
</a>

<a
        style={{ cursor:"pointer" }}
        href={void (0)}
        onClick={() =>
                      this.toggleModal("Rental Objects With Current Rent")
                    }
     >
    Click Me
    </a>

注意:我们也可以在 CSS 文件中使用 cursor:pointer 来代替

a:not([href]):not([tabindex]){
  cursor: pointer;
  color: #0086ce;
}

【讨论】:

    【解决方案2】:
    import { withRouter } from 'react-router-dom';
    import Button from '../../components/CustomButtons/Button';
    
     onRegister = () => {
        this.props.history.push('/signupAsTeacher');
      };
    <Button onClick={this.onRegister}> Contact Us </Button>
    
    export default withRouter(functionName);
    

    你必须先用Router导入。然后你应该给按钮点击事件的页面路径。最后一个是用Router导出的。

    【讨论】:

      【解决方案3】:

      Eslint 说要使用按钮:

      [eslint] Anchor 用作按钮。锚主要用于导航。请改用按钮元素。 [错误]

      <button
          type="button"
          onClick={this.onBtnClick.bind(this, key)}
      >
          {link[key]}
      </button>
      

      【讨论】:

        【解决方案4】:

        href="javascript:void(0)" 优于 href="#"

        href="#"会导致url改变。

        【讨论】:

        • href="javascript:void(0)" 会在你使用 linting 时引发警告:warning Script URL is a form of eval no-script-url
        【解决方案5】:

        您可以为链接设置cursor: pointer;,以实现真实url链接的行为:)

        <a onClick={this.handleClick} style={{cursor: 'pointer'}}>click me!</a>
        

        【讨论】:

          猜你喜欢
          • 2020-04-09
          • 2017-06-16
          • 2011-06-16
          • 2020-09-14
          • 2016-04-29
          • 2021-02-17
          • 1970-01-01
          • 2018-06-02
          • 2015-04-15
          相关资源
          最近更新 更多