前言在搜索页面中最近搜索和热门搜索标签使用 Flex 组件和FlexWrap.Wrap实现流式布局标签可以自动换行。本文将从源码出发深入讲解 Flex 流式布局的实现。一、最近搜索标签1.1 源码Flex({ wrap: FlexWrap.Wrap }) { ForEach(this.recentSearches, (tag: string) { Text(tag) .fontSize(13).fontColor(COLOR_TEXT_MAIN) .backgroundColor(COLOR_CARD_BG) .padding({ left: 14, right: 14, top: 8, bottom: 8 }) .borderRadius(BTN_RADIUS_FULL) .border({ width: 1, color: COLOR_DIVIDER }) .margin({ right: 8, bottom: 8 }) .onClick(() { this.searchText tag }) }, (tag: string) tag) } .width(100%)二、热门搜索标签2.1 源码Grid() { ForEach(HOT_TAGS, (tag: string) { GridItem() { Row() { SymbolGlyph($r(sys.symbol.flame)).fontSize(14).fontColor([COLOR_PRIMARY]) Text(tag).fontSize(13).fontColor(COLOR_TEXT_MAIN).margin({ left: 6 }) } .width(100%).height(44) .backgroundColor(COLOR_CARD_BG).borderRadius(CARD_RADIUS) .padding({ left: 12, right: 12 }) .onClick(() { this.searchText tag }) } }, (tag: string) tag) } .columnsTemplate(1fr 1fr 1fr) .columnsGap(8).rowsGap(8)三、Flex 与 Grid 的对比对比维度FlexGrid布局方式流式网格换行方式自动换行固定列数适用场景标签、按钮组规则网格对齐方式灵活对齐四、标签样式Text(tag) .fontSize(13).fontColor(COLOR_TEXT_MAIN) .backgroundColor(COLOR_CARD_BG) .padding({ left: 14, right: 14, top: 8, bottom: 8 }) .borderRadius(BTN_RADIUS_FULL) // 999 完全圆角 .border({ width: 1, color: COLOR_DIVIDER }) .margin({ right: 8, bottom: 8 })五、常见问题5.1 标签不换行问题标签超出屏幕宽度时没有换行。原因Flex 没有设置wrap: FlexWrap.Wrap。解决方案确保Flex组件的wrap属性设置为FlexWrap.Wrap。总结本文通过“海风日记“的搜索标签深入讲解了 Flex 流式布局FlexWrap.Wrap自动换行标签样式胶囊形、边框、圆角Grid 热门标签3 列网格点击交互点击标签填充搜索框下一篇文章将深入讲解最近搜索与热门搜索双状态切换敬请期待。如果这篇文章对你有帮助欢迎点赞、收藏⭐、关注你的支持是我持续创作的动力相关资源Flex 组件文档Grid 组件文档海风日记项目源码[HarmonyOS 开发者官网](https://atomgit.com/openharmony/docs开源鸿蒙跨平台社区