From aec039e42e5e3e41c526506a7e0678a5348ca467 Mon Sep 17 00:00:00 2001 From: shinya Date: Fri, 22 Aug 2025 19:30:55 +0800 Subject: [PATCH] fix: search bar enter with input search --- src/app/search/page.tsx | 13 +++++++++++++ src/components/SearchSuggestions.tsx | 22 ++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/src/app/search/page.tsx b/src/app/search/page.tsx index 3a19f5a..5ee3141 100644 --- a/src/app/search/page.tsx +++ b/src/app/search/page.tsx @@ -658,6 +658,19 @@ function SearchPageClient() { isVisible={showSuggestions} onSelect={handleSuggestionSelect} onClose={() => setShowSuggestions(false)} + onEnterKey={() => { + // 当用户按回车键时,使用搜索框的实际内容进行搜索 + const trimmed = searchQuery.trim().replace(/\s+/g, ' '); + if (!trimmed) return; + + // 回显搜索框 + setSearchQuery(trimmed); + setIsLoading(true); + setShowResults(true); + setShowSuggestions(false); + + router.push(`/search?q=${encodeURIComponent(trimmed)}`); + }} /> diff --git a/src/components/SearchSuggestions.tsx b/src/components/SearchSuggestions.tsx index d47f1db..acd21be 100644 --- a/src/components/SearchSuggestions.tsx +++ b/src/components/SearchSuggestions.tsx @@ -7,6 +7,7 @@ interface SearchSuggestionsProps { isVisible: boolean; onSelect: (suggestion: string) => void; onClose: () => void; + onEnterKey: () => void; // 新增:处理回车键的回调 } interface SuggestionItem { @@ -20,6 +21,7 @@ export default function SearchSuggestions({ isVisible, onSelect, onClose, + onEnterKey, }: SearchSuggestionsProps) { const [suggestions, setSuggestions] = useState([]); const containerRef = useRef(null); @@ -119,6 +121,26 @@ export default function SearchSuggestions({ return () => document.removeEventListener('mousedown', handleClickOutside); }, [isVisible, onClose]); + // 处理键盘事件,特别是回车键 + useEffect(() => { + const handleKeyDown = (e: KeyboardEvent) => { + if (e.key === 'Enter' && isVisible) { + // 阻止默认行为,避免浏览器自动选择建议 + e.preventDefault(); + e.stopPropagation(); + // 关闭搜索建议并触发搜索 + onClose(); + onEnterKey(); + } + }; + + if (isVisible) { + document.addEventListener('keydown', handleKeyDown, true); + } + + return () => document.removeEventListener('keydown', handleKeyDown, true); + }, [isVisible, onClose, onEnterKey]); + if (!isVisible || suggestions.length === 0) { return null; }