在React中,如何设置点击href什么都不做?

时间:2017-06-30 04:12:23

标签: javascript twitter-bootstrap reactjs bootstrap-4

我有以下html元素:

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

我需要href属性,因此bootstrap使用链接样式(颜色,光标)对元素进行样式设置。

问题是,如果我现在点击它会导致浏览器重定向。如何更新以上内容以不重定向浏览器onClick但仍然运行fields.push()

由于

11 个答案:

答案 0 :(得分:6)

您应该从 onClick 事件中调用 preventDefault 功能,如下所示:

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

您可以在您的用例中使用类似这样的内容:

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

答案 1 :(得分:4)

你应该考虑在反应组件中使用write方法clickHappens,而不是写入内联。希望它有效!

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

答案 2 :(得分:3)

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

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

答案 3 :(得分:1)

添加javscript:void(0):

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

答案 4 :(得分:1)

这是一个简单的解决方案,

  • 关于React类组件
class App extends React.Component {
  onClick() {
    console.log('onclick..')
  }

  render() {
    return (
      <a href={void(0)} onClick={this.onClick} >Click me</a>
    )
  }
}
  • 关于React功能组件(挂钩)
const App = () => {
  function onClick() {
    console.log('onclick..')
  }

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

React放弃了javascript:void(0)解决方案,并且href不一定接受空的属性值。

答案 5 :(得分:1)

使用 Ritesh 的答案,但没有“非布尔属性 href 收到为真”的问题,我只是用

替换了 标签
Houses

答案 6 :(得分:0)

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

在TypeScript href="javascript:void(0);"中会引发警告,因此还有其他方法可以跳过该警告

答案 7 :(得分:0)

像这样制作一个自定义组件;

import React from "react";

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

答案 8 :(得分:0)

使用 <button>

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

答案 9 :(得分:0)

  1. 网址中没有“#”;
  2. 无需调用 e.preventDefault();
  3. 简单~
 <a href={void(0)} onClick={()=>{console.log('...')}}>

答案 10 :(得分:-2)

尝试以下代码段

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