最近搜索与热门搜索双状态切换
前言
“海风日记“的搜索页面有两种状态:当搜索框为空时,显示最近搜索和热门搜索;当输入内容时,显示搜索结果。这种双状态切换提供了流畅的搜索体验。
本文将从源码出发,深入讲解搜索状态的切换逻辑。
一、双状态切换
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
- 开源鸿蒙跨平台社区
