如何解决子组件对话框未关闭
父组件中有一个按钮,通过它关闭子组件中的对话框。
父组件
handleMsgOpen = () => {
console.log('open called')
this.setState({ showMsg: true });
}
handleMsgClose = () => {
console.log('close called');
this.setState({ showMsg: false });
// this.props.authContext.logOut();
}
render{
return(
...some code
{this.state.showNotificationBell === true ?
< div className={styles.bell} onClick={this.handleMsgOpen}>
<img className={styles.bellIcon} src={'./DrawerAssets/bell.svg'} alt='bell' />
<div className={styles.bellNumber}>1</div>
<Msg
showMsg={this.state.showMsg}
handleMsgOpen={this.handleMsgOpen}
handleMsgClose={this.handleMsgClose}
/>
</div> : null}
...some code
)
}
消息组件(子组件)
import React from 'react';
import {
Grid,Typography,Container,Box,CircularProgress,Dialog,DialogActions,DialogContent,Button,DialogTitle,} from '@material-ui/core';
export interface MsgProps {
showMsg: boolean;
handleMsgOpen: any;
handleMsgClose: any;
}
export interface MsgState {
}
class Msg extends React.Component<MsgProps,MsgState> {
handleMsgOpen = () => {
this.props.handleMsgOpen();
}
handleMsgClose = () => {
this.props.handleMsgClose();
}
render() {
console.log('boolean',this.props.showMsg);
return (
<div>
<Dialog open={this.props.showMsg} onClose={this.handleMsgClose}>
<DialogTitle className="MsgTitle">Message title </DialogTitle>
<DialogContent className="MsgContent">Message Content</DialogContent>
<DialogActions>
<Grid container justify="center" spacing={2} style={{ paddingBottom: "2%" }}>
<Grid item>
<Button onClick={this.handleMsgClose} className="MsgButton" variant="outlined">
<div className="MsgLabel">
Logout
</div>
</Button>
</Grid>
</Grid>
</DialogActions>
</Dialog>
</div>
);
}
}
export default Msg;
第一次单击钟形图标对话框会正确打开。但是当我关闭它时,它显示Msg更改为false,这很好,但随后在父组件中再次调用handleMsgOpen并显示Msg更改为true,这不会不要让盒子关闭。
重新渲染父组件时可以触发onclick,但是为什么在第一次加载父组件时就不会发生这种情况?
解决方法
请勿将图标和消息放在同一格中。
这里的问题是,每当您单击消息将其关闭时,您的单击处理程序都会冒泡到图标中的父级,因为它被另一个单击处理程序所包围的div包围。基本上,您的子组件单击处理程序已注册,然后单击处理程序冒泡到父级并再次注册。
这称为事件冒泡。 您可以阅读有关此here
的信息<div
className={styles.bell}
onClick={this.handleMsgOpen}
>
<img
className={styles.bellIcon}
src={'./DrawerAssets/bell.svg'}
alt='bell'
/>
<div className={styles.bellNumber}>1</div>
</div> <--- Seperate the div here.
<Msg
showMsg={this.state.showMsg}
handleMsgOpen={this.handleMsgOpen}
handleMsgClose={this.handleMsgClose}
/>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。