最近搜索与热门搜索双状态切换
前言“海风日记“的搜索页面有两种状态当搜索框为空时显示最近搜索和热门搜索当输入内容时显示搜索结果。这种双状态切换提供了流畅的搜索体验。本文将从源码出发深入讲解搜索状态的切换逻辑。一、双状态切换1.1 状态判断// 搜索框为空时显示最近搜索 热门搜索 if (this.searchText.length 0) { // 最近搜索 if (this.recentSearches.length 0) { ... } // 热门搜索 this.hotSearchSection() } // 搜索框有内容时显示搜索结果 if (this.searchText.length 0) { // 搜索结果 this.searchResultsSection() }1.2 完整逻辑Scroll() { Column({ space: 24 }) { // 状态 1搜索框为空 → 显示推荐 if (this.searchText.length 0) { // 最近搜索 if (this.recentSearches.length 0) { this.recentSearchSection() } // 热门搜索 this.hotSearchSection() } // 状态 2搜索框有内容 → 显示搜索结果 if (this.searchText.length 0) { if (this.searchResults.length 0) { this.emptyResultSection() } else { this.searchResultList() } } } }二、状态清理2.1 清除最近搜索Button() { SymbolGlyph($r(sys.symbol.trash)).fontSize(16).fontColor([COLOR_TEXT_HINT]) } .backgroundColor(transparent).width(32).height(32) .onClick(() { this.recentSearches [] })2.2 清除搜索内容Button() { SymbolGlyph($r(sys.symbol.xmark_circle_fill)).fontSize(16).fontColor([COLOR_TEXT_HINT]) } .backgroundColor(transparent).width(28).height(28) .onClick(() { this.searchText })三、搜索结果的空状态if (this.searchResults.length 0) { Column({ space: 12 }) { Text().fontSize(48).margin({ top: 60, bottom: 12 }) Text(没有找到相关内容).fontSize(15).fontColor(COLOR_TEXT_SECONDARY) Text(换个关键词试试吧).fontSize(13).fontColor(COLOR_TEXT_HINT) } .width(100%).alignItems(HorizontalAlign.Center) }四、常见问题4.1 状态切换闪烁问题搜索框内容变化时页面内容闪烁。原因条件渲染导致组件重新创建。解决方案使用visibility属性替代条件渲染。总结本文通过“海风日记“的搜索页面深入讲解了双状态切换的实现搜索框为空显示最近搜索 热门搜索搜索框有内容显示搜索结果状态清理清除最近搜索和搜索内容空结果无匹配内容时的提示下一篇文章将深入讲解Grid 3 列展示热门标签敬请期待。如果这篇文章对你有帮助欢迎点赞、收藏⭐、关注你的支持是我持续创作的动力相关资源TextInput 组件文档Scroll 组件文档海风日记项目源码[HarmonyOS 开发者官网](https://atomgit.com/openharmony/docs开源鸿蒙跨平台社区