Stop parent component ripple being triggered from child component

ぐ巨炮叔叔 提交于 2019-12-13 03:13:03

问题


Let's say I have a simple code like:


<ListItem
  button={true}
>
  <Typography variant='caption' color='primary'>
            {value}
  </Typography>
  <Button
    onClick={foo}
  >
    Button
  </Button>
</ListItem>

When I click anything inside the ListItem the ripple effect is trigger, which is ok, but when I click the button I don't want the ripple effect of the parent component to be triggered. How do I do that?


回答1:


You can try to use disableRipple property of ListItem. Set it to true when clicking on button and set it to false when clicking on list item, something like:

const foo = () => this.setState(prevState => ({
  ...prevState,
  parentDisableRipple: true
}));
const enableRipple = () => this.state.parentDisableRipple && this.setState(prevState => ({
  ...prevState,
  parentDisableRipple: false
}));

return (
  <div>
    <Hello name={this.state.name} />
    <p>
      Start editing to see some magic happen :)
    </p>

    <ListItem button={true} 
              disableRipple={this.state.parentDisableRipple}
              onClick={enableRipple()}>
      <Typography variant='caption' color='primary'>
        {value}
      </Typography>
      <Button onClick={foo} >Button</Button>
    </ListItem>
  </div>
);

I created a STACKBLITZ to play with

UPDATE

There is a better solution by @Domino987 using onMouseDown and event.stopPropagation() (already mentioned here by @vasanthcullen).

I updated my STACKBLITZ with this solution




回答2:


Use event.stopPropagation() inside the click handler of the button. In your case, inside the foo() function



来源:https://stackoverflow.com/questions/56447828/stop-parent-component-ripple-being-triggered-from-child-component

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