Material-ui: How to stop propagation of click event in nested components

ε祈祈猫儿з 提交于 2020-08-27 02:53:11

问题


I have an IconMenu component inside a Paper component. I would like to prevent the propagation of the click event on the inner component (the IconMenu). That's what I came up with, without significant results (I also tried substituting onClick with onTouchTap, onMouseUp with same effects): the _iconMenuClick method is never called.

render() {
     return (
         <Paper onClick={this._onClick}>
             <IconMenu iconButtonElement={iconButtonElement} onClick={this._iconMenuClick}>
                 {menuItems}
             </IconMenu>
         </Paper>
     );
}

_iconMenuClick(event) {
    MenuItem.onClick(event);
    event.stopPropagation();
}

回答1:


In addition to using event.stopPropagation(); It is useful to note that it should be written within a onClick event handler.

I made the mistake of writing it inside an onChange event handler, and that wasn't working.

I found that solution here

EDIT:

<ListItem button onClick={this.handleListItemClick}>
-       <Checkbox onChange={this.handleCheckboxChange} />
+       <Checkbox onClick={this.handleCheckboxChange} />
      </ListItem>



回答2:


For stopping top node bubble events :-) event.stopPropagation(); event.preventDefault();




回答3:


The workaround I suggest is the following:

render() {
     return (
         <Paper onClick={this._onClick}>
             <IconMenu iconButtonElement={iconButtonElement}>
                 {menuItems}
             </IconMenu>
             ...
         </Paper>
     );
}

_onClick(event){
    if(event.target.innerText==""){ //Or any condition that distinguish the IconMenu from the Paper element
        event.stopPropagation();
        return 0;
    }
    //continue with normal behaviour
    ...
}


来源:https://stackoverflow.com/questions/34929267/material-ui-how-to-stop-propagation-of-click-event-in-nested-components

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!