【问题标题】:React Materials UI - How can I close two dialogs at the same timeReact Material UI - 如何同时关闭两个对话框
【发布时间】:2019-09-17 14:55:16
【问题描述】:

我有一个嵌套的弹出对话框组件(来自材料 UI),其中包括两个对话框,每个对话框都保持状态“打开”,此状态用于确定 dislog 窗口是否打开。当我关闭顶部对话框时是否可以同时关闭这两个状态,这需要将两个状态都设置为'false'

组件结构:

-Dialog1
 -Dialog2

为他们说明:

Dialog1: { open: true }
Dialog2: { open: true }

当我改变 Dialog2 的状态时,我可以设置 Dialog1 的状态吗?谁能帮忙?

【问题讨论】:

  • 是的,这是可能的。当第一个对话框即将关闭时,您需要更改两个对话框的状态。请提供一些代码,以便我进一步提供帮助

标签: reactjs material-ui


【解决方案1】:

有很多方法可以实现这一点,但这取决于您希望如何实现它或是否有意义。

由于没有提供具体的代码,会提供一些可以考虑的方式。

  1. Liffing state up
  2. 通过回调通知父母
  3. 上下文 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>;
}

【讨论】:

  • 父组件是指包裹这两个对话框的组件吗?
  • @HungryBird 是的。否则,您可以简单地将 child 对话框的打开/关闭状态设置为父对话框。
猜你喜欢
  • 1970-01-01
  • 2017-01-26
  • 2020-11-28
  • 1970-01-01
  • 2021-09-09
  • 2020-10-01
  • 2017-01-12
  • 2017-05-18
  • 2018-01-04
相关资源
最近更新 更多