【问题标题】:How do I send data from child component to parent component in React如何在 React 中将数据从子组件发送到父组件
【发布时间】: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;

如您所见,DialogBoxDrawer 的子级,两者都保存在不同的文件 DialogBox.js 和 Drawer.js

我可以通过 DialogBox 中名为 dilaogOpenProp 的道具发送布尔值,并且能够更改 dialogOpenState 值,但我还创建了一个方法在子组件 handleDialogClose() 中,它正在更改本地状态下 dialogOpenState 的布尔值的值,因为它的值也被变量名 dialogOpen 中的父组件使用 跟踪状态,但它没有得到更新和它创建 UI 错误

如何在调用其子方法 handleDialogClose()

【问题讨论】:

    标签: javascript reactjs react-hooks


    【解决方案1】:

    Drawer.js

    const handleDialogClose = () => {
        setDialogueOpen(false)
      }
         ....
          <DialogBox dilaogOpenProp={dialogOpen} handleDialogCloseProp={handleDialogClose} />
    

    DialogBox.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>
    

    不需要useState。你可以通过道具来做。

    【讨论】: