react中的事件冒泡不会停止使用 e.preventDefault()

IT技术 javascript reactjs ecmascript-6 dom-events
2021-04-30 05:11:36

我有一个<input>下 a <th>,输入有一个onChange事件,但是当输入被点击click时,<th>标签上会触发一个事件如何阻止click事件从 DOM 树上升到父事件侦听器?

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

2个回答

所以问题是,当您尝试通过单击来关注输入时,会在输入上触发 onClick 事件并将其传播给父级,

您有两种可能的解决方案:

第一:在事件的input和stopPropagation上添加一个onClick事件。

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

或者

二:检查targetonClick采取行动之前,事件

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

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

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

另一种选择是使用 stopPropagation 调用向输入添加点击处理程序:

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

MDN 详细信息currentTarget

当事件遍历 DOM 时,标识事件的当前目标。它总是指事件处理程序已附加到的元素,而不是 event.target 标识发生事件的元素。

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