简体   繁体   English

多个模式听同一个按键,我如何处理优先级?

[英]Multiple modals listening to the same keypress, how do I handle priority?

I'm trying to figure out the logic behind a problem, I'm hoping someone has any advice on how to solve this.我试图找出问题背后的逻辑,我希望有人对如何解决这个问题有任何建议。

The app is built with React.该应用程序是使用 React 构建的。

This is the flow of my applications:这是我的申请流程:

  • Use clicks on something使用点击某物
  • A modal pops up with a form that needs to be filled弹出一个模态框,需要填写一个表单
  • Once the form is filled the user clicks a "Submit" button填写表格后,用户单击“提交”按钮
  • A confirmation modal pops up on top of the first modal在第一个模态的顶部弹出一个确认模态

For accessibility and usability reasons I'd like both my modals to listen for the ESC keypress, so they can be easily cancelled from the keyboard.出于可访问性和可用性的原因,我希望我的两个模态都监听ESC按键,因此可以很容易地从键盘上取消它们。 I've implemented this and it works, but it's not great.我已经实现了这个并且它有效,但它不是很好。

I do this by calling an useEffect when the component is rendered:我通过在渲染组件时调用useEffect来做到这一点:

  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      if (e.isComposing || e.keyCode === 27) {
        // close modal
      }
    };

    document.addEventListener('keydown', handler);
    return () => {
      document.removeEventListener('keydown', handler);
    };
  }, []);

The problem I'm facing is that if both modals are open and ESC is pressed, both modals will close.我面临的问题是,如果两个模态都打开并按下ESC ,两个模态都会关闭。

How would you set priority for which modal gets closed first?您将如何设置首先关闭的模式的优先级? I've thought about having a global modal object where I can check which modal is the latest added, but that seems needlessly complex.我曾想过拥有一个全局模态 object ,我可以在其中检查最新添加的模态,但这似乎不必要地复杂。

Is there a simple solution I'm missing?我缺少一个简单的解决方案吗?

Here's a simple diagram explaining my problem.这是一个解释我的问题的简单图表。

在此处输入图像描述

in the handler of the first Modal check for the existance of the second Modal.在第一个 Modal 的处理程序中检查第二个 Modal 的存在。 If it's there, don't close the first one:)如果它在那里,请不要关闭第一个:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM