我有一个嵌套的弹出对话框组件(来自材料UI),其中包括两个对话框,每个对话框都保持状态“打开”,此状态用于确定日志窗口是否处于打开状态。当我关闭顶部对话框时是否有可能同时关闭这两个对话框,而这需要将两个状态都设置为“ false”
组件结构:
-Dialog1
-Dialog2
他们的状态:
Dialog1: { open: true }
Dialog2: { open: true }
答案 0 :(得分:1)
有多种方法可以实现此目标,但这取决于您要如何实现它或有意义。
由于未提供特定代码,因此将提供一些您可以考虑的方式。
您只需将对话框1和2的状态移动到父组件。
function Parent() {
const [dialogStates, setDialogStates] = useState({
isDialog1Open: false,
isDialog2Open: false
});
...
}
您可以提供在调用子对话框时要调用的功能。
查看下面的代码片段之类的伪伪代码。
function ParentDialog() {
const [isDialogOpen, setIsDialogOpen] = useState(false);
const [isChildDialogOpen, setIsChildDialogOpen] = useState(false);
return (
<Dialog isOpen={isDialogOpen}>
<ChildDialog onCancel={() => setIsDialogOpen(false)} />
</Dialog>
);
}
function ChildDialog({ onCancel }) {
return <Dialog onCancelClick={onCancel}>...</Dialog>;
}
您可以使用分派通知孩子们关闭父母。
这是实现它的方法之一。 (并且您可以使用this post使上下文API更可共享)。
const DialogStateContext = createContext();
const DialogActionContext = createContext();
function dialogReducer(state, action) {
... toggle dialog states here...
}
function DialogContainer({children}) {
const [state, dispatch] = useReducer(dialogReducer, initialState)
return (
<DialogStateContext.Provider value={state}>
<DialogActionContext.Provider value={dispatch}>
{children}
</DialogActionContext.Provider>
</DialogStateContext.Provider>
);
}
function ParentDialog() {
const state = useContext(DialogStateContext)
return (
<Dialog isOpen={state.isParentDialogOpen}>
<ChildDialog onCancel={() => setIsDialogOpen(false)} />
</Dialog>
);
}
function ChildDialog({ onCancel }) {
const dispatch = useContext(DialogActionContext)
return <Dialog onCancelClick={() => dispatch({type: 'close parent dialog'})}>...</Dialog>;
}