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

编程入门 行业动态 更新时间:2024-10-28 16:19:37
本文介绍了在 React 中,如何使锚点在点击时不执行任何操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我有以下 html 元素:

I have the following html element:

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

我需要 href 属性,因此引导程序使用链接样式(颜色、光标)为元素设置样式.

I need the href attribute so bootstrap styles the element with a link styling (color, cursor).

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

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 事件调用 preventDefault 函数:

You should call preventDefault function from onClick event like this:

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>
      ...
    )

这篇关于在 React 中,如何使锚点在点击时不执行任何操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-01 15:10:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/834243.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:操作   React   使锚点

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!