Javascript 停止从子组件触发的父组件涟漪
假设我有一个简单的代码,如:Javascript 停止从子组件触发的父组件涟漪,javascript,css,reactjs,material-ui,dom-events,Javascript,Css,Reactjs,Material Ui,Dom Events,假设我有一个简单的代码,如: <ListItem button={true} > <Typography variant='caption' color='primary'> {value} </Typography> <Button onClick={foo} > Button </Button> </ListItem> {value} 按钮 当我单击
<ListItem
button={true}
>
<Typography variant='caption' color='primary'>
{value}
</Typography>
<Button
onClick={foo}
>
Button
</Button>
</ListItem>
{value}
按钮
当我单击ListItem中的任何内容时,涟漪效应是触发器,这是可以的,但是当我单击按钮时,我不希望父组件的涟漪效应被触发。如何执行此操作?在按钮的单击处理程序中使用event.stopPropagation()。在您的例子中,在foo()函数中使用按钮的单击处理程序中的event.stopPropagation()。在您的例子中,在foo()函数中,您可以尝试使用
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>
);
constfoo=()=>this.setState(prevState=>({
…国家,
parentDisableRipple:正确
}));
const enableRipple=()=>this.state.parentDisableRipple&&this.setState(prevState=>({
…国家,
parentDisableRipple:false
}));
返回(
开始编辑以查看发生的奇迹:)
{value}
按钮
);
我创造了一个游戏
更新
@Domino987使用onMouseDown
和event.stopPropagation()
(这里@vasanthcullen已经提到过)进行了一次测试
我使用此解决方案更新了STACKBLITZ您可以尝试使用
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>
);
constfoo=()=>this.setState(prevState=>({
…国家,
parentDisableRipple:正确
}));
const enableRipple=()=>this.state.parentDisableRipple&&this.setState(prevState=>({
…国家,
parentDisableRipple:false
}));
返回(
开始编辑以查看发生的奇迹:)
{value}
按钮
);
我创造了一个游戏
更新
@Domino987使用onMouseDown
和event.stopPropagation()
(这里@vasanthcullen已经提到过)进行了一次测试
我用这个解决方案更新了我的STACKBLITZ这是我最终找到的解决方案,但不是真的那样。我不得不使用OnMouseDown属性并停止传播。这是我最终找到的解决方案,但不是真的那样。我必须使用OnMouseDown属性并停止传播。可爱又漂亮。没想到会这样。非常感谢。洛洛。可爱又漂亮。没想到会这样。非常感谢。