MYSQL 创建索引
2026/1/7 23:53:29
E:\source\aa2_agent12\ui\app\courses\[id]\page.tsx文件,点击【历史对话】按钮时会弹出下拉列表,现在需要增加一个功能:点击页面其他区域时隐藏这个下拉列表
添加了useRef导入:
import React, { useState, useEffect, useRef } from 'react'添加了 ref 和 useEffect 监听点击事件:
// Ref for history dropdown const historyDropdownRef = useRef<HTMLDivElement>(null) // 点击页面其他区域时关闭历史对话下拉列表 useEffect(() => { const handleClickOutside = (event: MouseEvent) => { if ( historyDropdownRef.current && !historyDropdownRef.current.contains(event.target as Node) ) { setShowHistoryDropdown(false) } } if (showHistoryDropdown) { document.addEventListener('mousedown', handleClickOutside) } return () => { document.removeEventListener('mousedown', handleClickOutside) } }, [showHistoryDropdown])将 ref 绑定到下拉菜单的容器上:
<div className='relative' ref={historyDropdownRef}>historyDropdownRef引用,绑定到包含按钮和下拉列表的容器上useEffect监听showHistoryDropdown的变化mousedown事件监听器现在点击页面其他区域时,历史对话下拉列表会自动关闭!