fix: search bar enter with input search

This commit is contained in:
shinya
2025-08-22 19:30:55 +08:00
parent 145111d3ca
commit aec039e42e
2 changed files with 35 additions and 0 deletions

View File

@@ -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)}`);
}}
/>
</div>
</form>

View File

@@ -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<SuggestionItem[]>([]);
const containerRef = useRef<HTMLDivElement>(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;
}