首页 > 解决方案 > 如何使用 react 和 materialUI 控制来自另一个模块的对话框

问题描述

我正在尝试借助按钮从另一个反应组件打开一个 materialUI 对话框组件。想要的结果是每次我单击按钮时它都会打开对话框。当前的结果是它仅在我每秒钟单击一次按钮时打开。

你们中有人知道为什么会这样吗?我必须使用 useeffect() Hook 吗?

这是带有按钮的父组件的代码片段:

const [showModal, setShowModal] = useState(false);

const saveButtonHandler1 = async () => {
    function showModalHandler() {
      setShowModal(!showModal);
      .... some other code.....
    }}

这是子对话框组件的代码片段:

export default function MaxWidthDialog(props) {
  useEffect(() => {
    handleClickOpen();
  }, []);

  const classes = useStyles();
  const [open, setOpen] = React.useState(false);
  const [fullWidth, setFullWidth] = React.useState(true);
  const [maxWidth] = React.useState("sm");

  const handleClickOpen = () => {
    setOpen(true);
    setTimeout(() => setOpen(false), 16000);
  };

  const handleClose = () => {
    setOpen(false);
    
  };

  /* const handleMaxWidthChange = event => {
    setMaxWidth(event.target.value);
  }; */

  const handleFullWidthChange = (event) => {
    setFullWidth(event.target.checked);
  };
 


  return (
    <React.Fragment>
      <Dialog
        fullWidth={fullWidth}
        maxWidth={maxWidth}
        open={open}
        onClose={handleClose}
        aria-labelledby="max-width-dialog-title"
      >
        <DialogTitle id="max-width-dialog-title"></DialogTitle>
        <DialogContent>
          <DialogContentText>
            <CanvasLoading />
          </DialogContentText>
        </DialogContent>
        <DialogActions></DialogActions>
      </Dialog>
    </React.Fragment>
  );
}

标签: reactjsmodal-dialogmaterial-uireact-component

解决方案


你好@Rainer 从你所说的我明白这一点:

  • 每次单击时都有一个带有按钮的父级打开对话框
  • 对话中有一个孩子

这是我使用您的一些代码创建的沙箱以及我所做的一些修改,您可以从以下内容开始:

import React, { useState } from "react";
import "./styles.css";
import MaxWidthDialog from "./Child";

export default function App() {
  const [isOpen, setIsOpen] = useState(false);

  const handleOpen = () => {
    setIsOpen(!isOpen);
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      {/*
      this is the child component with props to 
      get the status of dialog and to handle close the dialog
      */}
      <MaxWidthDialog
        isDialogOpened={isOpen}
        handleCloseDialog={() => setIsOpen(false)}
      />
      <button onClick={() => handleOpen()}>Open Dialog</button>
    </div>
  );
}

https://codesandbox.io/s/ecstatic-shamir-1ffso?file=/src/App.js

PS:不需要使用 UseEffect


推荐阅读