gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 20:58:44 30 4
gpt4 key购买 nike

我有一个 <input><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

最佳答案

所以事情是当你试图通过点击它来关注输入时,一个 onClick 事件在输入上被触发并传播到父级,

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

首先在input上添加一个onClick事件,并对该事件进行stopPropagation。

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

其次:在采取行动之前检查onClick事件中的target

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>
);

关于javascript - react 中的事件冒泡不会停止使用 e.preventDefault(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47837494/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com