【发布时间】:2020-12-28 05:02:56
【问题描述】:
我的父组件中有一个按钮,我正在使用它来关闭子组件中的对话框。
父组件
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
)
}
Msg 组件(子组件)
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,但是为什么在第一次加载父组件时它没有发生?
【问题讨论】:
标签: javascript reactjs onclick dialog