如何在页面切换时清空全局搜索框的输入内容?
解决全局搜索组件页面切换后残留内容的问题
问题分析
你当前的搜索组件用defaultValue给输入框赋值,属于非受控组件,只有初始渲染时会读取state.q的值,后续页面切换时即便路径变化,输入框内容也不会自动更新。另外,现有useEffect只处理了fromPath的重置,没有处理输入框内容的清空逻辑,导致切换页面后搜索框还留着之前的ID。
解决思路
- 改用受控组件:用
useState管理输入框的值,主动控制内容更新; - 监听页面切换:在
useEffect中监听location.pathname变化,切换到非搜索页时清空输入框; - 初始化赋值逻辑:仅在搜索页时从
state.q读取初始值,其他页面默认清空; - 同步状态与输入值:确保搜索、清空操作时,输入框状态和实际值完全同步。
修改后的代码
const searchPageRegex = /^\/org\/\d+\/search/; interface SearchWidgetProps { className?: string; } const SearchWidget = ({ className }: SearchWidgetProps) => { const navigate = useNavigate(); const location = useLocation() as Location & { state: { from: string | undefined }; }; const isSearchPage = searchPageRegex.test(location.pathname); const { state } = useLocalState(); const { organisationId } = useParams(); const [fromPath, setFromPath] = useState<string>(); // 用useState管理输入框值,改为受控组件 const [searchValue, setSearchValue] = useState<string>( isSearchPage ? (state.q as string) || '' : '' ); useEffect(() => { // 页面切换时:非搜索页则清空输入值和来源路径 if (!searchPageRegex.test(location.pathname)) { setSearchValue(''); setFromPath(undefined); } else if (location.state?.from) { // 进入搜索页时记录来源路径 setFromPath(location.state.from); } }, [location.pathname]); const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => { const newValue = e.target.value; setSearchValue(newValue); // 清空输入时跳转回来源页 if (newValue === '') { fromPath ? navigate(fromPath) : navigate('..'); } }; const onKeyPress: KeyboardEventHandler<HTMLInputElement> = (event) => { if (event.key === 'Enter' && searchValue.trim()) { const navState = isSearchPage ? undefined : { from: location }; navigate(`/org/${organisationId}/search?q=${searchValue.trim()}`, { state: navState }); } }; return ( <div className={`relative h-[42px] ${className}`}> <SearchIcon className="absolute left-2 m-2 h-6 w-6 stroke-1" /> <input type="text" name="search" aria-label="Search" value={searchValue} onChange={handleInputChange} title="Search" placeholder="Search ref. or end-to-end id" className="h-full w-full rounded-lg border-none bg-white p-2.5 pl-12 shadow-plain hover:shadow-plain-lg focus:shadow-plain-lg focus:outline-0 focus:ring-0" onKeyPress={onKeyPress} /> </div> ); }; export default SearchWidget;
关键修改说明
- 受控组件改造:用
searchValue状态替代defaultValue和ref,避免非受控组件的更新滞后问题,更符合React状态管理规范; - 页面切换处理:直接监听路径变化,非搜索页时强制清空输入值,确保切换页面后搜索框为空;
- 逻辑整合:将原
onChange的清空跳转逻辑与输入值更新合并,减少冗余代码; - 可选方案(非受控):如果不想改受控组件,也可以在
useEffect中直接操作DOM清空:useEffect(() => { if (!searchPageRegex.test(location.pathname)) { ref.current?.value = ''; setFromPath(undefined); } }, [location.pathname]);
内容的提问来源于stack exchange,提问作者user19625670
相关产品推荐
相关产品推荐

