如何在点击子元素时防止父元素的onClick事件触发?

3

我有这个组件的代码:

const myCardItem = ({ item }) => {

    function clickItem(){
        alert('Item clicked');
    }

    function clickMe(){
        alert('Button clicked');
    }

    return (
        <div className="myCardItem" onClick={clickItem}>
            <i className="fa fa-clock-o"/>&nbsp;{item.planDate}
            <br />
            <i className="fa fa-location-arrow"/>&nbsp;{item.destination}
            <br />
            <Button bsStyle="primary" onClick={clickMe}>Click Me</Button>
        </div>
    );
}

如果我点击按钮,会先出现以下内容: enter image description here 之后是: enter image description here 这很合理,因为按钮是myCardItem的子元素。但这不是我想要的。点击myCardItem将会加载一个新的视图,而点击按钮将会打开一个模态对话框。两者同时触发会破坏页面。
如何防止父级点击被调用?
在clickMe()中使用return false并不容易...

stopPropagation() - Deckerz
1个回答

6

使用event.stopPropagation()event.stopImmediatePropagation()可以停止事件冒泡并结束其被调用的事件冒泡。


2
提供一个修订版 OP 代码的解决方案是可行的方式。 - Junaid
你是正确的。 - simbathesailor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接