Reactjs 在外部单击或单击菜单时隐藏 div

Reactjs hide div when click outside or click men

我正在使用 tailwind 创建语言切换器组件 css。

语言选择器工作正常,但在 .

之外单击时无法隐藏语言

是否有语言切换器的反应组件?

请问如何隐藏 div 点击外部。

import { useState } from "react";
import { useTranslation } from "react-i18next";
import { MyanmarFlag, EnglishFlag } from "../assets/icons/svg_icons";

const LanguageSelector = () => {
  const [isOpen, setIsOpen] = useState(false);
  const { t, i18n } = useTranslation();

   const changeLanguage = (lng) => {
    i18n.changeLanguage(lng);
   };

  return (
<div className="flex justify-end p-4">
  <div className="relative">
    <button
      className="inline-flex justify-center w-full rounded-md border border-gray-300 shadow-sm px-4 py-2 
  bg-white text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2
   focus:ring-offset-gray-100 focus:ring-primary"
      onClick={() => setIsOpen(!isOpen)}
    >
      Select Language
    </button>
    {isOpen && (
      <div
        className="origin-top-right absolute right-0 mt-2 w-56 rounded-md shadow-lg 
  bg-white ring-1 ring-black ring-opacity-5 divide-y divide-gray-100
  focus:outline-none z-50"
      >
        <div className="py-1">
          <a
            className="group flex items-center px-4 py-2 text-sm text-gray-700
        hover:bg-primary hover:text-white"
            onClick={() => changeLanguage("my")}
          >
            <MyanmarFlag
              className="mr-3 h-5 w-5 text-gray-400 group-hover:text-white"
              aria-hidden="true"
            ></MyanmarFlag>
            Myanmar
          </a>
        </div>
        <div className="py-1">
          <a
            className="group flex items-center px-4 py-2 text-sm text-gray-700
        hover:bg-primary hover:text-white"
            onClick={() => changeLanguage("en")}
          >
            <EnglishFlag
              className="mr-3 h-5 w-5 text-gray-400 group-hover:text-white"
              aria-hidden="true"
            ></EnglishFlag>
            English
          </a>
        </div>
      </div>
    )}
  </div>
</div>
);
};

export default LanguageSelector;

您可以使用 useRef 挂钩并将事件侦听器绑定到您的 div,然后更改您的 isOpen 状态。