[英]How do I send data from child component to parent component in React
And I have a parent component code我有一个父组件代码
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);
I have a child component我有一个子组件
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;
As you can see DialogBox is child to Drawer both are saved in different file DialogBox.js & Drawer.js如您所见, DialogBox是Drawer 的子级,两者都保存在不同的文件 DialogBox.js 和 Drawer.js 中
I am able to send boolean value via prop named dilaogOpenProp in DialogBox and able to change dialogOpenState value but I have also created a method in child component handleDialogClose() which is changing the value of boolean value of dialogOpenState in local state ,Since its value is also used by parent component in variable name dialogOpen to track state but its not getting updated and its creating UI error我能够通过DialogBox 中名为dilaogOpenProp 的道具发送布尔值并能够更改dialogOpenState值,但我还在子组件handleDialogClose() 中创建了一个方法,该方法正在更改本地状态下dialogOpenState的布尔值的值,因为它的值是父组件在变量名dialogOpen 中也使用它来跟踪状态但它没有得到更新并且它创建 UI 错误
How do I update dialogOpen in parent and dilaogOpenState in child at same time during invocation of its child method handleDialogClose()如何在调用其子方法handleDialogClose()期间同时更新parent中的dialogOpen和child中的dilaogOpenState
Drawer.js抽屉.js
const handleDialogClose = () => {
setDialogueOpen(false)
}
....
<DialogBox dilaogOpenProp={dialogOpen} handleDialogCloseProp={handleDialogClose} />
DialogBox.js对话框.js
<Dialog
fullWidth
onClose={() => {}}
open={props.dilaogOpenProp}
maxWidth="xs"
sx={{
backdropFilter: "blur(5px)",
}}
>
<DialogTitle>Example Dialog</DialogTitle>
<DialogContent>Example Content Here</DialogContent>
<DialogActions>
<Button onClick={props.handleDialogCloseProp}>Close</Button>
</DialogActions>
</Dialog>
There is no need of useState.不需要 useState。 You can do it by props.
你可以通过道具来做到这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.