当我单击关闭按钮时,模态关闭功能不起作用

问题描述 投票:0回答:1
    const [modalOpen, setModalOpen] = useState(false);
    const openModal= ()=>{
        setModalOpen(true);
        
    }
    const closeModal = () => {
        setModalOpen(false);
      };

   
  return (
    <div className='bg-slate-300 dark:bg-slate-800 rounded-lg overflow-hidden' onClick={openModal}>
        </div>

        {modalOpen && (
                <div className='fixed inset-0 bg-slate-300 dark:bg-slate-900 bg-opacity-50 backdrop-blur flex justify-center items-center lg:w-6/12 sm:w-10/12 m-auto max-h-max rounded-md' visible>
                    <div className='dark:bg-slate-700 p-2 rounded'>
                        <span className='absolute top-0 right-0 m-2 text-red-600 text-lg cursor-pointer' onClick={closeModal}>
                            &times;
                        </span>
 
                        <button onClick={closeModal} className="mt-2 bg-gray-300 hover:bg-gray-400 px-3 py-1 rounded">
                            Close Modal
                        </button>
                    </div>
                </div>
            )}

    </div>
  )
}

这里我使用了 React 和 Tailwind CSS。它打开了这个模式,但是当我 单击关闭按钮或 x 时,它没有关闭。我现在做什么。

reactjs button onclick modal-dialog
1个回答
0
投票

您必须将整个组件(包括按钮和模式)包装在 React Fragment 中。

确保打开模式的 div。 这是固定代码。


      const [modalOpen, setModalOpen] = useState(false);
      const openModal= ()=>{
          setModalOpen(true);
          
      }
      const closeModal = () => {
          setModalOpen(false);
        };

     
    return (
      <>
      <div className='bg-slate-300 dark:bg-slate-800 rounded-lg overflow-hidden' onClick={openModal}>
        Open
          </div>
          <div>
          {modalOpen && (
                  <div className='fixed inset-0 bg-slate-300 dark:bg-slate-900 bg-opacity-50 backdrop-blur flex justify-center items-center lg:w-6/12 sm:w-10/12 m-auto max-h-max rounded-md' visible>
                      <div className='dark:bg-slate-700 p-2 rounded'>
                          <span className='absolute top-0 right-0 m-2 text-red-600 text-lg cursor-pointer' onClick={closeModal}>
                              &times;
                          </span>

                          <button onClick={closeModal} className="mt-2 bg-gray-300 hover:bg-gray-400 px-3 py-1 rounded">
                              Close Modal
                          </button>
                      </div>
                  </div>
              )}

      </div>
      </>
    )
© www.soinside.com 2019 - 2024. All rights reserved.