反应onClick和preventDefault()链接刷新/重定向? [英] React onClick and preventDefault() link refresh/redirect?

查看:506
本文介绍了反应onClick和preventDefault()链接刷新/重定向?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用react渲染链接:

I'm rendering a link with react:

render: ->
  `<a className="upvotes" onClick={this.upvote}>upvote</a>`

然后,上面我有upvote函数:

Then, above I have the upvote function:

upvote: ->
  // do stuff (ajax)

在链接之前我已经跨越了那个地方但是我需要切换到链接,这是麻烦 - 每次我点击 .upvotes 页面都会刷新,到目前为止我尝试过:

Before link I had span in that place but I need to switch to link and here's the trouble - every time I click on .upvotes the page gets refreshed, what I've tried so far:

event.preventDefault() - 无效。

event.preventDefault() - not working.

upvote: (e) ->
  e.preventDefault()
  // do stuff (ajax)

event.stopPropagation() - 无效。

event.stopPropagation() - not working.

upvote: (e) ->
  e.stopPropagation()
  // do stuff (ajax)

返回false - 不工作。

return false - not working.

upvote: (e) ->
  // do stuff (ajax)
  return false

我也是在我的index.html中使用jQuery尝试了以上所有内容,但似乎没有任何效果。我该怎么做,我做错了什么?我已经检查了event.type并且它是点击所以我想我应该能够以某种方式避免重定向?

I've also tried all of the above using jQuery in my index.html, but nothing seems to work. What should I do here and what I'm doing wrong? I've checked event.type and it's click so I guess I should be able to avoid redirect somehow?

对不起,对于React来说,我是新手。

Excuse me, I'm a rookie when it comes to React.

谢谢!

推荐答案

React事件实际上是Synthetic Events,而不是Native Events。正如它写的那样这里

React events are actually Synthetic Events, not Native Events. As it is written here:


事件委托:React实际上并没有将事件处理程序附加到节点本身。当React启动时,它会使用单个事件侦听器开始侦听顶级的所有事件。安装或卸载组件时,只需在内部映射中添加或删除事件处理程序。当事件发生时,React知道如何使用此映射调度它。当映射中没有事件处理程序时,React的事件处理程序是简单的无操作。

Event delegation: React doesn't actually attach event handlers to the nodes themselves. When React starts up, it starts listening for all events at the top level using a single event listener. When a component is mounted or unmounted, the event handlers are simply added or removed from an internal mapping. When an event occurs, React knows how to dispatch it using this mapping. When there are no event handlers left in the mapping, React's event handlers are simple no-ops.

尝试使用Use Event.stopImmediatePropagation

upvote: (e) ->
  e.stopPropagation();
  e.nativeEvent.stopImmediatePropagation();

这篇关于反应onClick和preventDefault()链接刷新/重定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆