为什么点击按钮时 mui 对话框不关闭?

问题描述 投票:0回答:1

在我的 React 项目中,我有一个全屏打开的对话框,但单击关闭图标按钮时不会关闭。

打开对话框的组件:

interface IContentCardProps {
  content: IContentProps;
}

const ContentCard = ({ content }: IContentCardProps) => {
  const { user } = useUser();
  const [open, setOpen] = useState<boolean>(false);

  return (
    <Box
      p={2}
      height="300px"
      maxWidth="250px"
      display="flex"
      flexDirection="column"
      justifyContent="space-between"
      border={`1px solid ${blue.main}`}
      sx={{
        cursor: "pointer",
        ":hover": { boxShadow: `0px 0px 3px 1px ${blue.main}` },
      }}
      onClick={() => setOpen(true)}
    >
      <Typography
        variant="body1"
        gutterBottom
        fontWeight={700}
        color={blue.main}
      >
        {content?.title}
      </Typography>
      <Typography
        variant="caption"
        marginBottom={1}
        lineHeight={1.6}
        textOverflow="ellipsis"
        display="-webkit-box "
        overflow="hidden"
        sx={{ WebkitLineClamp: 8, WebkitBoxOrient: "vertical" }}
      >
        {content?.description}
      </Typography>
      <Box pt={1} display="flex" alignItems="center" borderTop={`1px solid ${grey.extraLight}`}>
        <SvgIcon component={AccessTimeOutlinedIcon} sx={{ mr: 1 }} />
        <Typography variant="caption" fontWeight={700}>
          <span>{content?.duration}</span> min
        </Typography>
      </Box>
      <ContentDialog open={open} setOpen={setOpen} />
    </Box>
  );
};

export default ContentCard;

对话框组件:

const Transition = forwardRef(function Transition(
  props: TransitionProps & {
    children: React.ReactElement;
  },
  ref: React.Ref<unknown>,
) {
  return <Slide direction="left" ref={ref} {...props} />;
});

interface IContentDialogProps {
  open: boolean;
  setOpen: React.Dispatch<React.SetStateAction<boolean>>;
}

const ContentDialog = ({ open, setOpen }: IContentDialogProps) => {
  return (
    <>
      <Dialog fullScreen open={open} onClose={() => setOpen(false)} TransitionComponent={Transition}>
        <AppBar sx={{ position: "relative", backgroundColor: blue.main }}>
          <Toolbar>
            <IconButton edge="start" color="inherit" onClick={() => setOpen(false)} aria-label="close">
              <CloseIcon />
            </IconButton>
          </Toolbar>
        </AppBar>
        <Box> content</Box>
      </Dialog>
    </>
  );
};

SetOpen 似乎不适用于对话框,我不知道为什么......
如果有人有想法那就太好了!

reactjs material-ui dialog
1个回答
0
投票

点击关闭按钮会触发点击事件,也会冒泡,无意中触发父元素的点击事件。这会导致在

onClick={() => setOpen(true)}
内的元素上执行
ContentCard
函数。为了防止这种情况,您可以在关闭按钮的单击事件上使用
stopPropagation
。方法如下:

onClose={(e) => {
  e.stopPropagation();
  setOpen(false);
}}
© www.soinside.com 2019 - 2024. All rights reserved.