next.js onClick不使用addEventUntil mousedown

bis0qfac  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(159)

我有下面的React组件,这是一个配置文件按钮,打开一个菜单,有3个选项:我的配置文件,设置和注销。
问题是,onClick事件不起作用(在这种情况下,不打印console.log)
但是,如果我删除useEffect,其中包含addEventEvent,当它被点击时关闭菜单,onClick on标签就可以工作。
我必须做些什么才能让它工作而不删除事件?
React代码:

'use client'
// Importe as bibliotecas necessárias
import React, { useState, useRef, useEffect } from 'react'
//ICON
import { FaCircleUser } from 'react-icons/fa6'
import {
  AiOutlineUser,
  AiOutlineSetting,
  AiOutlineLogout
} from 'react-icons/ai'

const ProfileButton = () => {
  // Estado para controlar a exibição do menu
  const [isMenuOpen, setIsMenuOpen] = useState(false)

  // Referência para o botão de perfil
  const profileButtonRef = useRef()

  // Função para fechar o menu quando clicar fora do botão
  const handleClickOutside = event => {
    if (
      profileButtonRef.current &&
      !profileButtonRef.current.contains(event.target)
    ) {
      setIsMenuOpen(false)
    }
  }

 

  // Adiciona um event listener para fechar o menu ao clicar fora
  useEffect(() => {
    document.addEventListener('mousedown', handleClickOutside)

    // Remove o event listener ao desmontar o componente
    return () => {
      document.removeEventListener('mousedown', handleClickOutside)
    }
  }, [])

  return (
    <div className="relative inline-block text-left">
      {/* Botão de perfil */}
      <button
        ref={profileButtonRef}
        className="text-3xl text-zinc-700 py-2 px-4 rounded-full focus:outline-none cursor-pointer"
        onClick={() => setIsMenuOpen(!isMenuOpen)}
      >
        <FaCircleUser />
      </button>

      {/* Menu de opções */}
      {isMenuOpen && (
        <div className="origin-top-right absolute right-0 mt-2 w-50 bg-white border border-gray-300 rounded-md shadow-lg z-50">
          <div className="py-1">
            <a
              href="#"
              className="px-4 py-2 text-gray-800 hover:bg-gray-200 flex items-center z-999"
              onClick={() => console.log('My Profile')}
            >
              <AiOutlineUser className="mr-2" size={18} />
              My Profile
            </a>
            <a
              href="#"
              className="px-4 py-2 text-gray-800 hover:bg-gray-200 flex items-center"
              onClick={() => console.log('Settings')}
            >
              <AiOutlineSetting className="mr-2" size={18} />
              Configurações
            </a>
          </div>
          <div className="border-t border-gray-300">
            <a
              href="#"
              className="px-4 py-2 text-gray-800 hover:bg-gray-200 flex items-center"
              onClick={() => console.log('logout')}
            >
              <AiOutlineLogout className="mr-2" size={18} />
              Sair
            </a>
          </div>
        </div>
      )}
    </div>
  )
}

export default ProfileButton

字符串
删除了addEventList,但需要它来关闭菜单时,单击外部。

ulmd4ohb

ulmd4ohb1#

这个问题是由于事件传播引起的。要解决这个问题,您可以修改handleClickOutside函数来检查单击是否在菜单和按钮内。如果单击在按钮或菜单内,则该函数不应该关闭菜单。
试试这个

import React, { useState, useRef, useEffect } from 'react'
// ... [Other imports]

const ProfileButton = () => {
  const [isMenuOpen, setIsMenuOpen] = useState(false)
  const profileButtonRef = useRef()
  const menuRef = useRef() // Ref for the menu

  const handleClickOutside = event => {
    if (
      profileButtonRef.current &&
      !profileButtonRef.current.contains(event.target) &&
      menuRef.current && // Ensure menuRef is set
      !menuRef.current.contains(event.target) // Check if click is outside the menu
    ) {
      setIsMenuOpen(false)
    }
  }

  useEffect(() => {
    document.addEventListener('mousedown', handleClickOutside)
    return () => {
      document.removeEventListener('mousedown', handleClickOutside)
    }
  }, [])

  return (
    <div className="relative inline-block text-left">
      {/* ... [Profile Button Code] */}

      {/* Menu de opções */}
      {isMenuOpen && (
        <div ref={menuRef} className="origin-top-right absolute right-0 mt-2 w-50 bg-white border border-gray-300 rounded-md shadow-lg z-50">
          {/* ... [Menu Items Code] */}
        </div>
      )}
    </div>
  )
}

export default ProfileButton

字符串

相关问题