简体   繁体   English

在 React 中,如何使锚点在点击时不执行任何操作?

[英]In React, how can I cause anchors to do nothing on click?

I have the following html element:我有以下 html 元素:

<a href onClick={() => fields.push()}>Add Email</a>

I need the href attribute so bootstrap styles the element with a link styling (color, cursor).我需要 href 属性,以便引导 styles 具有链接样式(颜色、光标)的元素。

Problem is, if I click that now it causes the browser to redirect.问题是,如果我现在单击它,它会导致浏览器重定向。 How can I update the above to not redirect the browser onClick but still run fields.push() ?如何更新以上内容以不重定向浏览器 onClick 但仍运行fields.push()

You should call preventDefault function from onClick event like this:您应该像这样从onClick事件调用preventDefault函数:

class App extends React.Component {
  onClick = (e) => {
    e.preventDefault()
    console.log('onclick..')
  }
  render() {
    return (
      <a href onClick={this.onClick} >Click me</a>
    )
  }
}

You can use something like this particular to your use case:您可以针对您的用例使用类似的东西:

    const renderEmails = ({ fields }) => (
      ...
      <a href onClick={(e) => {
        e.preventDefault()
        fields.push()
      }}>Add Email</a>
      ...
    )

Here's a simple solution,这是一个简单的解决方案,

On React class component在 React 类组件上

class App extends React.Component {
  onClick() {
    console.log('onclick..')
  }

  render() {
    return (
      <a href={void(0)} onClick={this.onClick} >Click me</a>
    )
  }
}

React is dropping the javascript:void(0) solution and the href doesn't certainly accept the empty attribute value. React 正在放弃javascript:void(0)解决方案,并且 href 肯定不接受空属性值。

Basically what react wants us to do is to use a different component, for instance a button.基本上,react 希望我们做的是使用不同的组件,例如按钮。 We can always make a button look like a link using CSS(and thus, won't contain href and the complexity to remove it's behaviour).我们总是可以使用 CSS 使按钮看起来像一个链接(因此,不会包含href和删除它的行为的复杂性)。 So, instead of using an anchor tag as a button, use the button element itself.因此,不要使用锚标记作为按钮,而是使用按钮元素本身。 Hope it makes sense.希望这是有道理的。

You should consider write method clickHappens in react component instead of writing this inline.您应该考虑在反应组件中编写方法 clickHappens 而不是内联编写此方法。 Hope it works!希望它有效!

<a href onClick={(e) => {e.preventDefault(); fields.push()}}> Add Email </a>

e.preventDefault()添加到 onClick 并添加href="#"属性

<a href="#" onClick={(e) => { e.preventDefault(); fields.push(); }}>Add Email</a>

Using Ritesh's answer, but without the issue of "Received true for a non-boolean attribute href", I simply swapped out the <a> tag with a <span>使用 Ritesh 的答案,但没有“非布尔属性 href 接收为真”的问题,我只是用 <span> 替换了 <a> 标签

class App extends React.Component {
  onClick = (e) => {
    e.preventDefault()
    console.log('onclick..')
  }
  render() {
    return (
      <span onClick={this.onClick}>Click me</span>
    )
  }
}

Just make a custom component like this;只需像这样制作一个自定义组件;

import React from "react";

export default function Link({ to, className, children }) {
  return (
    <a
      href={to}
      className={className}
      onClick={(e) => {
        e.preventDefault();
      }}
    >
      {children}
    </a>
  );
}

Use a <button>使用<button>

 button { background: none!important; border: none; padding: 0!important; color: #069; text-decoration: underline; cursor: pointer; }
 <button type="button"> My link </button>

try this code;试试这个代码;

<a href={undefined} onClick={() => {/*function code*/}}></a>

void(0) returns undefined. void(0) 返回未定义。 so you should write directly undefined on React because javascript:URL deprecated by React.所以你应该直接在 React 上写 undefined 因为 javascript:URL 被 React 弃用了。

https://reactjs.org/blog/2019/08/08/react-v16.9.0.html#deprecating-javascript-urls https://reactjs.org/blog/2019/08/08/react-v16.9.0.html#deprecating-javascript-urls

This solution can also be helpful:此解决方案也很有帮助:

<a href={void(0)} onClick={(e)=>{
e.preventDefault();
}}>

Here is a simple solution, it's worked for me:这是一个简单的解决方案,它对我有用:

   <a href={'/'} onClick={
                          (e) => {
                              e.preventDefault()
                              openProfileBox()
                          }
                      }
target="self" title='profile'>
{iconStyle(CgProfile)}
</a>

The "href" is a link for the index page, but with "e.preventDefault()" method, I can deny the link from work and call the second function to work successfully. “href”是索引页面的链接,但使用“e.preventDefault()”方法,我可以拒绝链接工作并调用第二个函数成功工作。

I use it this way:我这样使用它:

const url = '#'

<a href={url} onClick={() => alert('Test')}>Any text</a>

I use this one liner to conditionally redirect, or not.我使用这个衬垫来有条件地重定向或不重定向。 Give null value to href, and it will be rendered as a dummy Anchor tag.将 null 值赋给 href,它将被渲染为一个虚拟的 Anchor 标签。

<a href={isDisableRedirect ? null : REDIRECT_LINK}>link</a>

// rendered as `<a>link</a>` in DOM.

Solution for Javascript:void(0);解决方案Javascript:void(0); in React JS is to use the href="preventDefault()" .在 React JS 中是使用href="preventDefault()" This will prevent the default behaviour of a link causing the page to refresh or navigate away.这将防止导致页面刷新或导航离开的链接的默认行为。

  1. no '#' in URL; URL 中没有“#”;
  2. no need to call e.preventDefault();无需调用e.preventDefault();
  3. simple~简单~
 <a href={void(0)} onClick={()=>{console.log('...')}}>

添加 javscript:void(0):

<a href="javascript:void(0);" onClick={() => fields.push()}>Add Email</a>

fields.push()}>Add Email fields.push()}>添加电子邮件

In TypeScript href="javascript:void(0);"在 TypeScript 中href="javascript:void(0);" throws warning, so there any other way to skip that warnings引发警告,因此还有其他方法可以跳过该警告

试试下面的代码片段

<a href="true" ....>

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

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