ReactJS Modal с материальным пользовательским интерфейсом

Я пытаюсь сделать многоразовое подтверждение с помощью пользовательского интерфейса материала, но когда я нажимаю ОТМЕНА или ОК, модальное окно не закрывается.

Код здесь:

https://codesandbox.io/s/lucid-hoover-sput6?file=/src/App.js

Я не могу понять, почему поп не исчезает.

ЛЭ: добавил сюда код, чтобы он остался

ConfirmModal.js

import React from "react";
import { Button } from "@material-ui/core";
import Dialog from "@material-ui/core/Dialog";
import DialogActions from "@material-ui/core/DialogActions";
import DialogContent from "@material-ui/core/DialogContent";
import DialogContentText from "@material-ui/core/DialogContentText";

const ConfirmModal = (props) => {
  const { content, open, setOpen, onConfirm } = props;

  return (
    <Dialog
      open={open}
      onClose={() => setOpen(false)}
      aria-labelledby="dialog-title"
    >
      <DialogContent>
        <DialogContentText>{content}</DialogContentText>
      </DialogContent>
      <DialogActions>
        <Button autoFocus onClick={() => setOpen(false)} color="primary">
          Cancel
        </Button>
        <Button
          onClick={() => {
            setOpen(false);
            onConfirm();
          }}
          color="primary"
        >
          OK
        </Button>
      </DialogActions>
    </Dialog>
    // </div>
  );
};

export default ConfirmModal;

App.js

import React, { useState } from "react";
import { IconButton } from "@material-ui/core";
import { Input as InputIcon } from "@material-ui/icons";

import ConfirmModal from "./ConfirmModal";

export default function App() {
  const [confirmOpen, setConfirmOpen] = useState(false);

  const handleLogout = () => {
    console.log("this hould logout the user");
  };

  return (
    <div className="App">
      <h2>Press the button below so the confirmation modal appears </h2>
      <IconButton color="inherit" onClick={() => setConfirmOpen(true)}>
        <InputIcon />
        <ConfirmModal
          content="Are you sure you want to leeeave us ?"
          open={confirmOpen}
          setOpen={setConfirmOpen}
          onConfirm={handleLogout}
        />
      </IconButton>
    </div>
  );
}

person nipuro    schedule 14.10.2020    source источник


Ответы (1)


Выдвиньте модальное окно из кнопки. События отмены / подтверждения / фонового клика модального окна распространяются (всплывают) до кнопки открытия (IconButton), а его onClick обработчик просто повторно открывает модальное окно, устанавливая confirmOpen состояние true.

export default function App() {
  const [confirmOpen, setConfirmOpen] = useState(false);

  const handleLogout = () => {
    console.log("this hould logout the user");
  };

  return (
    <div className="App">
      <h2>Press the button below so the confirmation modal appears </h2>
      <IconButton color="inherit" onClick={() => setConfirmOpen(true)}>
        <InputIcon />
      </IconButton>
      <ConfirmModal
        content="Are you sure you want to leeeave us ?"
        open={confirmOpen}
        setOpen={setConfirmOpen}
        onConfirm={handleLogout}
      />
    </div>
  );
}
person Drew Reese    schedule 14.10.2020
comment
отлично, он работает, но что вы имеете в виду под его обработчиком onClick - это просто повторное открытие модального окна. на какой onClick вы ссылаетесь? - person nipuro; 14.10.2020
comment
@nipuro События щелчка от модального всплывающего окна до кнопки, используемой для открытия модального окна. Я обновил ответ, надеюсь, немного большей ясности. - person Drew Reese; 14.10.2020