import { View, Image, Text } from "@tarojs/components"; import { Input } from "@nutui/nutui-react-taro"; import { useEffect, useMemo, useRef } from "react"; import { useListState } from "@/store/listStore"; import img from "@/config/images"; import { withAuth } from "@/components"; import "./index.scss"; import Taro from "@tarojs/taro"; const ListSearch = () => { const { searchValue, updateState, updateSearchPageState, getSearchHistory, clearHistory, searchSuggestion, } = useListState() || {}; const { searchHistory = [], suggestionList, isShowSuggestion, } = useListState()?.searchPageState || {}; const ref = useRef(null); useEffect(() => { getSearchHistory(); return () => { handleClear(); }; }, []); useEffect(() => { if (ref?.current) { ref.current.focus(); } }, [ref.current]); const regex = useMemo(() => { return new RegExp(searchValue, "gi"); }, [searchValue]); // 是否显示清空图标 const isShowClearIcon = searchValue && searchValue?.length > 0; // 是否显示搜索历史 const isShowHistory = searchHistory && searchHistory?.length > 0; /** * @description 输入 * @param value */ const handleChange = (value: string) => { updateState({ searchValue: value }); if (value) { searchSuggestion(value); } else { updateSearchPageState({ isShowSuggestion: false, }); } }; /** * @description 点击清空输入内容 */ const handleClear = () => { updateState({ searchValue: "" }); updateSearchPageState({ isShowSuggestion: false }); }; /** * @description 点击历史搜索 * @param value */ const handleHistoryClick = (item: { id: number; title: string }) => { updateState({ searchValue: item?.title }); handleSearch(item?.title); }; /** * @description 清空历史搜索 */ const handleClearHistory = () => { clearHistory(); }; /** * @description 点击联想词 */ const handleSuggestionSearch = (val: string) => { updateState({ searchValue: val }); updateSearchPageState({ isShowSuggestion: false, }); handleSearch(val); }; /** * @description 点击搜索 */ const handleSearch = (val?: string) => { if (!val) { return; } Taro.navigateTo({ url: `/game_pages/searchResult/index`, }); }; return ( <> {/* 搜索 */} {isShowClearIcon && ( )} handleSearch(searchValue)}> 搜索 {/* 联想词 */} {isShowSuggestion && ( {(suggestionList || [])?.map((item) => { // 替换匹配文本为高亮版本 const highlightedText = item.replace(regex, (match) => { // 如果匹配不到,则返回原文本 if (!match) return match; return `${match}`; }); return ( handleSuggestionSearch(item)} > ); })} )} {/* 历史搜索 */} {!isShowClearIcon && ( 历史搜索 清空 {isShowHistory && ( {(searchHistory || [])?.map((item) => { if (!item?.title) { return null; } return ( handleHistoryClick(item)} > {item?.title} ); })} )} )} ); }; export default withAuth(ListSearch);