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

查看:33
本文介绍了反应 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() - 不起作用.

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

event.stopPropagation() - 不工作.

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

返回 false - 不起作用.

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

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

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 事件实际上是合成事件,而不是原生事件.正如此处所写:

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.

尝试使用Event.stopImmediatePropagation:

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

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

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