本文介绍了反应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:

尝试使用Use Event.stopImmediatePropagation

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

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

09-05 13:12
查看更多