简体   繁体   English

带有 React Hook 的多个模态

[英]Multiple Modals with React Hooks

I´m building some modals for fun but I can´t make it work for multiple modals.我正在构建一些有趣的模态,但我不能让它适用于多个模态。

useModal hook使用模态钩子

import { useState } from 'react';

const useModal = () => {

    const [isShowing, setIsShowing] = useState(false);

    const toggle = () => {
        setIsShowing(!isShowing);
    }

    return {
        isShowing,
        toggle,
    }
};

export default useModal;

Modal component模态组件

import React, { useEffect } from 'react';

const Modal = (props) => {

    const { toggle, isShowing, children } = props;

    useEffect(() => {

        const handleEsc = (event) => {
            if (event.key === 'Escape') {
                toggle()
            }
        };

        if (isShowing) {    
            window.addEventListener('keydown', handleEsc);
        }

        return () => window.removeEventListener('keydown', handleEsc);

    }, [isShowing, toggle]);

    if (!isShowing) {
        return null;
    }

    return (
        <div className="modal">
            <button onClick={ toggle } >close</button>
            { children }
        </div>
    )
}

export default Modal

in my Main component在我的主要组件中

If I do this the only modal in the page works fine如果我这样做,页面中唯一的模式就可以正常工作

const { isShowing, toggle } = useModal();
...
<Modal isShowing={ isShowing } toggle={ toggle }>first modal</Modal>

but when I try to add another one it doesn´t work.但是当我尝试添加另一个时它不起作用。 it doesn´t open any modal它不会打开任何模态

const { isShowingModal1, toggleModal1 } = useModal();
const { isShowingModal2, toggleModal2 } = useModal();
...
<Modal isShowing={ isShowingModal1 } toggle={ toggleModal1 }>first modal</Modal>
<Modal isShowing={ isShowingModal2 } toggle={ toggleModal2 }>second modal</Modal>

what I´m doing wrong?我做错了什么? thank you谢谢你

if you want to check it out please go to https://codesandbox.io/s/hopeful-cannon-guptw?fontsize=14&hidenavigation=1&theme=dark如果你想看看,请去https://codesandbox.io/s/hopeful-cannon-guptw?fontsize=14&hidenavigation=1&theme=dark

Try that:试试看:

const useModal = () => {
  const [isShowing, setIsShowing] = useState(false);

  const toggle = () => {
    setIsShowing(!isShowing);
  };

  return [isShowing, toggle];
};

then:然后:

export default function App() {
  const [isShowing, toggle] = useModal();
  const [isShowingModal1, toggleModal1] = useModal();
  const [isShowingModal2, toggleModal2] = useModal();

if you have multiple modal then dynamically inject <div> inside the page body and map modal to it.如果您有多个模态,则在页面正文中动态注入<div>并将模态映射到它。 to create div use,创建 div 使用,

    var divTag = document.createElement("div");
    divTag.setAttribute('id', 'modal');
    document.getElementsByTagName('body')[0].appendChild(divTag);
    document.getElementById('modal').innerHTML = modalHtML;

This should work.这应该有效。

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

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