首页 > 解决方案 > 带有 React Hooks 的多模态

问题描述

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

使用模态钩子

import { useState } from 'react';

const useModal = () => {

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

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

    return {
        isShowing,
        toggle,
    }
};

export default useModal;

模态组件

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

在我的主要组件中

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

const { isShowing, toggle } = useModal();
...
<Modal isShowing={ isShowing } toggle={ toggle }>first modal</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>

我做错了什么?谢谢你

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

标签: reactjsreact-hooks

解决方案


试试看:

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

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

  return [isShowing, toggle];
};

然后:

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

推荐阅读