问题描述
假设我有一个简单的代码,例如:
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>
当我单击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?
推荐答案
您可以尝试使用ListItem
的disableRipple
属性.单击按钮时将其设置为true
,单击列表项时将其设置为false
,例如:
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>
);
我创建了一个 STACKBLITZ 来玩
更新
有一个(@vasanthcullen已在此处提及).
There is a better solution by @Domino987 using onMouseDown
and event.stopPropagation()
(already mentioned here by @vasanthcullen).
我使用此解决方案更新了STACKBLITZ
I updated my STACKBLITZ with this solution
这篇关于停止从子组件触发父组件波纹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!