如何使用onClick处理程序在React组件中创建链接

How to create a link in React component with onClick handler?

本文关键字:组件 创建 链接 React 何使用 onClick 处理 程序      更新时间:2023-09-26

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

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

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

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

我读过的所有教程都使用<a>之外的另一个元素——可点击的<span><div>等,但我想使用<a>

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

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

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

href="#"将导致url更改。

对于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文件中使用光标:指针

a:not([href]):not([tabindex]){
  cursor: pointer;
  color: #0086ce;
}
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导出。

Eslint说要使用按钮:

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

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

这是最简单的方法之一:

<a href="/" onClick={this.handleClick}></a>