在事件中冒泡的事件不会停止使用e.preventDefault() [英] event bubbling in react doesn't stop using e.preventDefault()

查看:114
本文介绍了在事件中冒泡的事件不会停止使用e.preventDefault()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在<th>下有一个<input>,输入具有onChange事件,但是,单击输入时,在<th>标记上触发了click事件.如何阻止click事件从DOM树上升到父事件侦听器?

I have an <input> under a <th>, the input has an onChange event, however when the input is clicked a click event is being fired on the <th> tag. How to stop the click event from going up the DOM tree to the parent event-listener?

const App = () => (
  <div style={styles}>
    <table>
      <th onClick={()=>alert('fire')}>
        name
        <input onChange={e=>{e.preventDefault();alert('change text')}}/>
      </th>
    </table>
  </div>
);

尝试激活输入 https://codesandbox.io/s/wq3rj2m00w

推荐答案

如果只希望在直接单击th单击处理程序时将其触发,则可以检查目标:

If you only want the th click handler to fire when it is clicked on directly, you can check the target:

<th onClick={e => {
   if (e.currentTarget === e.target) {
     alert('fire');
   }
}}>

另一种选择是通过stopPropagation调用将点击处理程序添加到输入中:

The other option is to add a click handler to the input with a stopPropagation call:

<input onChange={e=>{e.preventDefault();alert('change text')}} onClick={e => e.stopPropagation()}/>

currentTarget上的MDN详细信息:

MDN details on currentTarget:

标识事件的当前目标,因为事件遍历DOM.它始终是指事件处理程序已附加到的元素,而不是event.target,后者标识发生事件的元素.

Identifies the current target for the event, as the event traverses the DOM. It always refers to the element to which the event handler has been attached, as opposed to event.target which identifies the element on which the event occurred.

https://developer.mozilla.org/en -US/docs/Web/API/Event/currentTarget

这篇关于在事件中冒泡的事件不会停止使用e.preventDefault()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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