gpt4 book ai didi

javascript - React - 如何防止子组件的点击事件

转载 作者:行者123 更新时间:2023-12-01 00:36:09 26 4
gpt4 key购买 nike

在标记为重复之前,它是不同的。我有这样的场景,我想将一些非预定义的元素放入子组件中。当用户单击该元素时,它会在父元素事件上触发。单击子项时如何停止父项上的事件触发器?让我用下面的例子来解释更多 -

所以,它基本上是一个 Accordion 列表,通过单击每个项目标题 div ( list-container__item____title ),将显示正文 div ( list-container__item____body )。

现在,在标题 div 内,我有一个链接 ( list-container__item____title--link ),它打开一个覆盖层(子组件)。叠加内容来自API调用,其内容为HTML。我无法为该元素添加更多功能,因为我不知道其中包含什么,它基于用户的选择。如果 HTML 中有一些可点击的元素,如 anchor 、按钮等,则状态 ( activeItem ) 将更新为空 ( '' ) 值。结果是相应的项目被折叠。有什么办法可以防止这种情况发生吗?

import React from 'react';

class DiamondFilters extends React.Component {

constructor(props) {
super(props);

this.state = {
activeItem: ''
};
}

handleItemToggle = (name) => {
if (this.state.activeItem === name) {
this.setState({ activeItem: '' })
} else {
this.setState({ activeItem: name })
}
}

render() {
return (
<div className="menu">
<div className="list-container">
<div className={`list-container__item ${this.state.activeItem === "item1" ? 'active' : ''}`}>
<div className="list-container__item____title" onClick={() => this.handleItemToggle('item1')}>
<a className="list-container__item____title--link">Click Here 1</a>
<OverlayModal modalType="full" modalName="item1" />
</div>
<div className="list-container__item____body">
<p>There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable.</p>
</div>
</div>
<div className={`list-container__item ${this.state.activeItem === "item2" ? 'active' : ''}`}>
<div className="list-container__item____title" onClick={() => this.handleItemToggle('item2')}>
<a className="list-container__item____title--link">Click Here 2</a>
<OverlayModal modalType="full" modalName="item2" />
</div>
<div className="list-container__item____body">
<p>There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable.</p>
</div>
</div>
</div>
</div>
);
}

}

最佳答案

您可以将 OverlayModal 包装在另一个组件(“Click Muncher”)中,以防止任何点击冒泡:

const ClickMuncher = ({ children }) => {
return <div onClick={e => e.stopPropagation()}>{children}</div>;
};

并像这样使用它:

<div className="list-container__item____title" onClick={() => this.handleItemToggle('item1')}>
<a className="list-container__item____title--link">Click Here 1</a>
<ClickMuncher>
<OverlayModal modalType="full" modalName="item1" />
</ClickMuncher>
</div>

关于javascript - React - 如何防止子组件的点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58119831/

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