【发布时间】:2025-12-12 21:10:01
【问题描述】:
而且我有一个父组件代码
const Drawer = props => {
const theme = useTheme();
const { history } = props;
const [open, setOpen] = React.useState(false);
const [dialogOpen,setDialogueOpen] = React.useState(false)
const handleDialogueOpen = () => {
setDialogueOpen(true)
}
return (
<Box sx={{ display: 'flex' }}>
<AppBar position="fixed" open={open}>
<Toolbar>
<Typography variant="h6" noWrap component="div">
XYZ
</Typography>
<Button onClick={handleDialogueOpen}>Filter</Button>
</Toolbar>
</AppBar>
<DialogBox dilaogOpenProp={dialogOpen}/>
</Box>
);
}
export default withRouter(Drawer);
我有一个子组件
const DialogBox = (props) => {
const [dialogOpenState, setOpen] = React.useState(props.dilaogOpenProp);
React.useEffect(() => {
setOpen(props.dilaogOpenProp);
}, [props.dilaogOpenProp]);
const handleDialogClose = () => {
setOpen(false)
}
return (
<>
<CssBaseline />
<Dialog
fullWidth
onClose={() => {}}
open={dialogOpenState}
maxWidth="xs"
sx={{
backdropFilter: "blur(5px)",
}}
>
<DialogTitle>Example Dialog</DialogTitle>
<DialogContent>Example Content Here</DialogContent>
<DialogActions>
<Button onClick={handleDialogClose}>Close</Button>
</DialogActions>
</Dialog>
</>
);
}
export default DialogBox;
如您所见,DialogBox 是 Drawer 的子级,两者都保存在不同的文件 DialogBox.js 和 Drawer.js
我可以通过 DialogBox 中名为 dilaogOpenProp 的道具发送布尔值,并且能够更改 dialogOpenState 值,但我还创建了一个方法在子组件 handleDialogClose() 中,它正在更改本地状态下 dialogOpenState 的布尔值的值,因为它的值也被变量名 dialogOpen 中的父组件使用 跟踪状态,但它没有得到更新和它创建 UI 错误
如何在调用其子方法 handleDialogClose()
【问题讨论】:
标签: javascript reactjs react-hooks