前言
在搜索页面中,最近搜索和热门搜索标签使用 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 的对比
| 对比维度 | Flex | Grid |
|---|---|---|
| 布局方式 | 流式 | 网格 |
| 换行方式 | 自动换行 | 固定列数 |
| 适用场景 | 标签、按钮组 | 规则网格 |
| 对齐方式 | 灵活 | 对齐 |
四、标签样式
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
- 开源鸿蒙跨平台社区