reactjs - 如何使用 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>
);
}
解决方案
你好@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
推荐阅读
- python - 链接 GET 和 POST 请求不好吗?
- huggingface-transformers - “ValueError:您必须在使用 Trainer 时指定 input_ids 或 inputs_embeds”
- python - 从密码生成 RSA 公钥和私钥对
- class - 我正在学习 kotlin,我观察到当我们通过点运算符访问主函数中的类的属性时,它不会显示任何错误
- javascript - 从控制台日志中用 Javascript 构建直方图?
- angular - 如何为 Bigcommerce API 修复 Angular 中的 CORS 错误
- python - 在 python 中为不同的步骤名称显示不明确的步骤异常
- python - 包装脚本,将记录另一个带参数的脚本的执行时间
- intellij-idea - 在空手道/IntelliJ 中等待并行功能完成
- java - 从任何地方使用 Java Runtime 执行 cl 命令