带有 React Hook 的多个模态

han*_*ome 1 reactjs react-hooks

我正在构建一些有趣的模态,但我不能让它适用于多个模态。

使用模态钩子

import { useState } from 'react';

const useModal = () => {

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

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

    return {
        isShowing,
        toggle,
    }
};

export default useModal;
Run Code Online (Sandbox Code Playgroud)

模态组件

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
Run Code Online (Sandbox Code Playgroud)

在我的主要组件中

如果我这样做,页面中唯一的模式就可以正常工作

const { isShowing, toggle } = useModal();
...
<Modal isShowing={ isShowing } toggle={ toggle }>first modal</Modal>
Run Code Online (Sandbox Code Playgroud)

但是当我尝试添加另一个时它不起作用。它不会打开任何模态

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

我做错了什么?谢谢你

如果您想查看,请访问https://codesandbox.io/s/hopeful-cannon-guptw?fontsize=14&hidenavigation=1&theme=dark

gad*_*ori 5

试试看:

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

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

  return [isShowing, toggle];
};
Run Code Online (Sandbox Code Playgroud)

然后:

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

  • 嗯,它与钩子无关,它是纯粹的 es6 JS。 (2认同)