有很多方法可以实现这一点,但这取决于您希望如何实现它或是否有意义。
由于没有提供具体的代码,会提供一些可以考虑的方式。
-
Liffing state up。
- 通过回调通知父母
- 上下文 API
1。提升状态
您可以简单地将对话框 1 和 2 的状态移动到父组件。
function Parent() {
const [dialogStates, setDialogStates] = useState({
isDialog1Open: false,
isDialog2Open: false
});
...
}
2。通过回调通知父母
您可以提供调用子对话框时要调用的函数。
查看下面的类似 sn-p 的排序伪代码。
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>;
}
3。上下文 API
您可以使用调度通知父级从子级关闭。
这是实现它的方法之一。
(并且您可以使用 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>;
}