你能用一个按钮改变两个组件的状态吗



我正试图用React+MUI创建一个入职或三模态系列。基本上,单击模态中的按钮后,它将转到下一个模态。我看过一些包,但它们对于我的用例来说很复杂。实现这一目标的最佳方法是什么?我可以尝试更新模态的当前状态以关闭,同时更新另一个模态状态以打开,这可能吗?

const [open, setOpen] = React.useState(false);

const [openTwo, setOpenTwo] = React.useState(false);

const handleOpen = () => setOpen(true);
const handleClose = () => setOpen(false).setOpenTwo(true);

<Modal
open={openTwo}
onClose={handleClose}>
{Modal content here
</Modal>

您在handleClose((中使用箭头函数隐式返回setOpen(false(,您可以阅读更多关于箭头函数here的信息,但重要的是

if the body requires additional lines of processing, you'll need to re-introduce braces PLUS the "return" (arrow functions do not magically guess what or when you want to "return"):

由于您正在调用setOpen和setOpenTwo,因此不需要通过返回任何内容

const handleClose = () => {
setOpen(false)
setOpenTwo(true)
}

最新更新