我有一个<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>
);
最佳答案
所以问题是,当您尝试通过单击输入来关注输入时,会在输入上触发 onClick 事件并将其传播到父级,
您有两种可能的解决方案:
首先:在输入上添加 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
事件中的目标
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/