[英]mui Dialog not closing properly
I have a problem with a dialog not closing properly.我有一个对话框没有正确关闭的问题。 Dialog open is set to a state variable intialized as true, and immediately changed to false. Dialog open 设置为 state 变量初始化为 true,并立即更改为 false。 The dialog doesn't close properly, and the app does not respond.对话框没有正确关闭,应用程序没有响应。
I have demonstrated this in the following sandbox where the button can not be clicked, though it should be available.我已经在下面的沙箱中演示了这一点,其中按钮无法单击,但它应该可用。
EDIT: To make clear.编辑:明确。 The dialog is not supposed to ever open.该对话框不应该打开。 But the button outside the dialog (with the text "a button") should be clickable.但是对话框外的按钮(带有文本“a button”)应该是可点击的。
https://codesandbox.io/s/adoring-benji-300mcm https://codesandbox.io/s/adoring-benji-300mcm
This code will work:此代码将起作用:
export default function App() {
const [open, setOpen] = useState(false);
console.log(open);
return (
<div>
<Dialog open={open} height="100px" width="100px" id="111">
<button onClick={() => setOpen(false)}>close</button>
</Dialog>
<button onClick={() => console.log("click")}>a button</button>
</div>
);
}
You don't need the useEffect to change state immediately, you could just pass false as a desired initial value to the state. Now the button "a button" is working.您不需要 useEffect 立即更改 state,您可以将 false 作为所需的初始值传递给 state。现在按钮“一个按钮”正在工作。
EDIT : To make the code working without removing useEffect, add conditional rendering:编辑:要使代码在不删除 useEffect 的情况下工作,请添加条件渲染:
export default function App() {
const [open, setOpen] = useState(true);
useEffect(() => setOpen(false), []);
console.log(open);
return (
<div>
{open && (
<Dialog open={open} height="100px" width="100px" id="111">
<button onClick={() => setOpen(false)}>close</button>
</Dialog>
)}
<button onClick={() => console.log("click")}>a button</button>
</div>
);
}
My best guess is that in your code the Dialogue gets rendered anyways, even though it is not displayed, because at first "open" was true.我最好的猜测是,在你的代码中,对话无论如何都会被渲染,即使它没有显示,因为起初“打开”是真的。 So in order for it not to be rendered, or to be rendered conditionally, you should check state.所以为了让它不被渲染,或者有条件地渲染,你应该检查state。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.