阻止从子组件触发父组件纹波



假设我有一个简单的代码,如下所示:


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

当我单击 ListItem 中的任何内容时,会触发涟漪效果,这没关系,但是当我单击按钮时,我不希望触发父组件的涟漪效果。我该怎么做?

您可以尝试使用 ListItem 的属性disableRipple 。单击按钮时将其设置为true,单击列表项时将其设置为false,如下所示:

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>
);

我创建了一个堆栈闪电战来玩

更新

@Domino987使用 onMouseDownevent.stopPropagation()(@vasanthcullen 已经在这里提到(和<ListItemSecondaryAction>包装器,有一个更好的解决方案。

我用这两种解决方案更新了我的 STACKBLITZ

在按钮的点击处理程序中使用 event.stopPropagation((。在您的情况下,在 foo(( 函数内部

<ListItem button={true} matRipple #parent>
 <Typography variant='caption' color='primary' matRipple [matRippleTrigger]="parent"
   [matRippleDisabled]="true">
    {value}
 </Typography>
 <Button onClick={foo}>
    Button
 </Button>
</ListItem>

你需要这样的东西:添加模板变量,该元素应进行动画处理。并使用[matRippleTrigger]选项触发子项的父纹波。

最新更新