如何防止单击时嵌套 React 组件中的事件冒泡? [英] How can I prevent event bubbling in nested React components on click?
本文介绍了如何防止单击时嵌套 React 组件中的事件冒泡?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是一个基本组件.
和 都有 onClick 函数.我只想触发
上的 onClick,而不是
.我怎样才能做到这一点?
Here's a basic component. Both the <ul>
and <li>
have onClick functions. I want only the onClick on the <li>
to fire, not the <ul>
. How can I achieve this?
我尝试过 e.preventDefault()、e.stopPropagation(),但无济于事.
I've played around with e.preventDefault(), e.stopPropagation(), to no avail.
class List extends React.Component {
constructor(props) {
super(props);
}
handleClick() {
// do something
}
render() {
return (
<ul
onClick={(e) => {
console.log('parent');
this.handleClick();
}}
>
<li
onClick={(e) => {
console.log('child');
// prevent default? prevent propagation?
this.handleClick();
}}
>
</li>
</ul>
)
}
}
// => parent
// => child
推荐答案
我遇到了同样的问题.我发现 stopPropagation 确实有效.我会将列表项拆分为一个单独的组件,如下所示:
I had the same issue. I found stopPropagation did work. I would split the list item into a separate component, as so:
class List extends React.Component {
handleClick = e => {
// do something
}
render() {
return (
<ul onClick={this.handleClick}>
<ListItem onClick={this.handleClick}>Item</ListItem>
</ul>
)
}
}
class ListItem extends React.Component {
handleClick = e => {
e.stopPropagation(); // <------ Here is the magic
this.props.onClick();
}
render() {
return (
<li onClick={this.handleClick}>
{this.props.children}
</li>
)
}
}
这篇关于如何防止单击时嵌套 React 组件中的事件冒泡?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文