当前位置: 首页 > news >正文

HarmonyOS7 电商首页拆解:Flex 嵌套如何撑起完整首页

文章目录

      • 电商首页先拆大区块
      • 数据结构先看这里
      • 状态变量负责让页面动起来
      • 布局代码怎么读
      • 交互逻辑别藏太深
      • 使用时我会怎么改
      • 完整代码
      • 代码里的几个细节
      • 常见改造坑
      • 写在最后

电商首页不是一个属性能写完,搜索、Banner、分类、秒杀区都要分层处理。

这里我会多讲一点代码。很多教程只把完整代码贴出来,看着是完整了,但读者真正改项目时还是不知道该动哪里。下面这几段会把数据、状态、布局和事件拆开说。

电商首页先拆大区块

这个案例对应的是「电商首页」。如果只是运行一下效果,当然很快;但真要把它改进自己的项目里,最好先把页面分成“数据层、状态层、布局层、交互层”四块。

我比较推荐这种读法:先看interface定义,再看@State,最后看build()里的ColumnRowFlex怎么嵌套。这样不容易被一长串样式绕晕。

数据结构先看这里

这份代码里的核心数据模型是BannerItem / CategoryEntry / FlashSaleProduct。它决定了页面每一项需要哪些字段,比如标题、描述、颜色、状态、价格、数量、角标等。很多 ArkUI 页面写得乱,根源不是布局,而是数据字段没想清楚。

如果你要接真实接口,优先改这一层。接口字段名和页面字段名不一致也没关系,可以在请求完成后做一次映射,别把接口返回结构直接塞进 UI 里。那样短期省事,后面改样式会很难受。

状态变量负责让页面动起来

这个案例里最关键的状态是currentBanner / cartCount。它不是摆设,页面里的选中、展开、切换、数量变化、输入内容,基本都靠它驱动。

写 HarmonyOS7 ArkUI 页面时,我会刻意把“会变的东西”和“不会变的静态数据”分开。像banners / categories / flashProducts这种列表数据负责提供内容,currentBanner / cartCount负责描述当前用户操作后的界面状态。这样读代码时很清楚:数据从哪里来,界面为什么变。

布局代码怎么读

布局部分不要从第一行样式读到最后一行,这样很累。先找最外层容器,看页面是纵向结构还是横向结构;再看每个区域内部是RowColumn还是Flex

这个案例的布局重点是:复杂首页要按区域拆,搜索、Banner、分类、商品卡不要塞在同一层。

如果你调页面时发现内容挤压、对齐不准、间距失控,优先检查这几个地方:固定宽高是不是太多,layoutWeightBlank是否用对,列表项里长文本有没有设置省略,Flex 换行条件是否满足。

交互逻辑别藏太深

这个页面的交互主线是:点击分类会增加购物车数量,Banner 和秒杀区组成完整首页氛围。

小案例里直接在.onClick()里改状态没问题,读起来也直观。但如果后面业务变复杂,比如要请求接口、弹确认框、写缓存,就别把逻辑全塞在事件回调里。可以拆成一个私有方法,让 UI 代码只表达“点了什么”,具体怎么处理交给方法。

使用时我会怎么改

如果你只是学习布局,直接运行下面代码就行。如果你准备放进项目里,我建议按这个顺序改:先替换数据数组,再调整颜色和字体,最后再改交互逻辑。

还有一个小经验:不要一开始就把所有东西拆成组件。先让页面跑通,等你发现某个卡片、按钮组、列表项重复出现两三次,再抽成@Builder或单独组件。这样代码会更贴近真实需求。

完整代码

/** * Flex 嵌套布局:电商首页综合布局 * 知识点:Flex 容器嵌套,实现复杂电商首页布局结构 */ interface BannerItem_48yv { id: number title: string subTitle: string bgColor: string emojiIcon: string } interface CategoryEntry { id: number name: string emojiIcon: string bgColor: string } interface FlashSaleProduct { id: number productName: string currentPrice: string originalPrice: string soldPercent: number emojiIcon: string } @Entry @Component struct EcommerceHomeFlexPage { @State currentBanner: number = 0 @State cartCount: number = 0 private banners: BannerItem_48yv[] = [ { id: 1, title: '618年中大促', subTitle: '全场最高优惠 50%', bgColor: '#FF4D4D', emojiIcon: '🎉' }, { id: 2, title: '新品首发', subTitle: 'HarmonyOS 5.0 开发者套件', bgColor: '#007DFF', emojiIcon: '🚀' }, { id: 3, title: '会员专享', subTitle: '限时积分兑换', bgColor: '#9B59B6', emojiIcon: '👑' }, ] private categories: CategoryEntry[] = [ { id: 1, name: '手机', emojiIcon: '📱', bgColor: '#FFE8E8' }, { id: 2, name: '电脑', emojiIcon: '💻', bgColor: '#E8F0FF' }, { id: 3, name: '耳机', emojiIcon: '🎧', bgColor: '#E8FFE8' }, { id: 4, name: '平板', emojiIcon: '📟', bgColor: '#FFF3E0' }, { id: 5, name: '手表', emojiIcon: '⌚', bgColor: '#F3E8FF' }, { id: 6, name: '相机', emojiIcon: '📷', bgColor: '#E8FFFF' }, { id: 7, name: '家电', emojiIcon: '🏠', bgColor: '#FFFFE8' }, { id: 8, name: '更多', emojiIcon: '⋯', bgColor: '#F5F5F5' }, ] private flashSaleItems: FlashSaleProduct[] = [ { id: 1, productName: '蓝牙耳机 Pro', currentPrice: '¥199', originalPrice: '¥499', soldPercent: 75, emojiIcon: '🎧' }, { id: 2, productName: '智能手表', currentPrice: '¥399', originalPrice: '¥799', soldPercent: 88, emojiIcon: '⌚' }, { id: 3, productName: '充电宝 20000', currentPrice: '¥89', originalPrice: '¥159', soldPercent: 60, emojiIcon: '🔋' }, { id: 4, productName: '机械键盘', currentPrice: '¥299', originalPrice: '¥599', soldPercent: 45, emojiIcon: '⌨️' }, ] build() { Column() { // ========== 顶部导航栏 ========== // Flex Row:Logo + 搜索框(flexGrow) + 购物车图标 Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center }) { Text('🛒 商城') .fontSize(18) .fontWeight(FontWeight.Bold) .fontColor('#FFFFFF') .flexShrink(0) Row({ space: 8 }) { Text('🔍').fontSize(14).fontColor('#BBBBBB') Text('搜索商品...') .fontSize(14) .fontColor('#BBBBBB') .layoutWeight(1) } .layoutWeight(1) // flexGrow: 1 .height(36) .backgroundColor('rgba(255,255,255,0.2)') .borderRadius(18) .padding({ left: 12, right: 12 }) .margin({ left: 12, right: 12 }) Stack({ alignContent: Alignment.TopEnd }) { Text('🛒') .fontSize(24) if (this.cartCount > 0) { Text(this.cartCount.toString()) .fontSize(10) .fontColor('#FFFFFF') .backgroundColor('#FF4D4D') .width(16).height(16) .borderRadius(8) .textAlign(TextAlign.Center) } } .flexShrink(0) } .width('100%') .padding({ left: 16, right: 16, top: 16, bottom: 12 }) .backgroundColor('#007DFF') // ========== Banner 区 ========== // Flex Row:三个 Banner 水平布局,中间大,两侧小 Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Stretch }) { ForEach(this.banners, (banner: BannerItem_48yv, idx: number) => { Column({ space: 8 }) { Text(banner.emojiIcon).fontSize(idx === 1 ? 40 : 28) Text(banner.title) .fontSize(idx === 1 ? 16 : 13) .fontWeight(FontWeight.Bold) .fontColor('#FFFFFF') Text(banner.subTitle) .fontSize(idx === 1 ? 12 : 10) .fontColor('rgba(255,255,255,0.85)') .maxLines(1) } .justifyContent(FlexAlign.Center) .alignItems(HorizontalAlign.Center) .backgroundColor(banner.bgColor) .borderRadius(idx === 1 ? 14 : 10) .flexGrow(idx === 1 ? 2 : 1) // 中间 banner flexGrow:2,两侧各 flexGrow:1 .height(idx === 1 ? 120 : 100) .margin(idx === 0 ? { right: 8 } : idx === 2 ? { left: 8 } : { left: 0, right: 0 }) .onClick(() => { this.currentBanner = idx }) }) } .width('100%') .padding({ left: 16, right: 16, top: 12, bottom: 4 }) // ========== 分类导航 ========== // 外层 Flex Row Wrap,内层每项 Flex Column Flex({ direction: FlexDirection.Row, wrap: FlexWrap.NoWrap, justifyContent: FlexAlign.SpaceAround }) { ForEach(this.categories, (cat: CategoryEntry) => { // 每个分类项:Flex Column Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Text(cat.emojiIcon) .fontSize(24) .width(48).height(48) .textAlign(TextAlign.Center) .backgroundColor(cat.bgColor) .borderRadius(14) Text(cat.name) .fontSize(12) .fontColor('#555555') .margin({ top: 6 }) } .flexBasis('12.5%') // 8等分 .padding({ top: 4, bottom: 4 }) .onClick(() => { this.cartCount++ }) }) } .width('100%') .padding({ left: 8, right: 8, top: 12 }) .backgroundColor('#FFFFFF') // ========== 限时秒杀 ========== Column({ space: 12 }) { // 标题行:Flex Row Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center }) { Text('⚡ 限时秒杀') .fontSize(16) .fontWeight(FontWeight.Bold) .fontColor('#FF4D4D') Text('02:45:30') .fontSize(14) .fontColor('#FFFFFF') .backgroundColor('#FF4D4D') .padding({ left: 8, right: 8, top: 4, bottom: 4 }) .borderRadius(6) .margin({ left: 10 }) Blank() Text('全部 ›') .fontSize(14) .fontColor('#007DFF') } .width('100%') // 商品横排:Flex Row(等分) Flex({ direction: FlexDirection.Row, justifyContent: FlexAlign.SpaceBetween }) { ForEach(this.flashSaleItems, (product: FlashSaleProduct) => { // 每个商品:Flex Column Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) { // 商品图 Text(product.emojiIcon) .fontSize(32) .width(72).height(72) .textAlign(TextAlign.Center) .backgroundColor('#F5F5F5') .borderRadius(10) // 价格 Text(product.currentPrice) .fontSize(16) .fontWeight(FontWeight.Bold) .fontColor('#FF4D4D') .margin({ top: 8 }) Text(product.originalPrice) .fontSize(11) .fontColor('#BBBBBB') .decoration({ type: TextDecorationType.LineThrough }) // 进度条 Column({ space: 3 }) { Progress({ value: product.soldPercent, total: 100, type: ProgressType.Linear }) .width('100%') .color('#FF4D4D') .backgroundColor('#FFE0E0') .style({ strokeWidth: 4, enableScanEffect: false }) Text('已售 ' + product.soldPercent + '%') .fontSize(10) .fontColor('#FF8C00') } .width('100%') .margin({ top: 6 }) } .flexBasis('23%') // 四等分,每项约占 23%(留间距) .padding({ top: 8, bottom: 8 }) }) } .width('100%') } .padding({ left: 16, right: 16, top: 14, bottom: 14 }) .backgroundColor('#FFFFFF') .margin({ top: 8 }) } .width('100%') .height('100%') .backgroundColor('#F5F6FA') } }

代码里的几个细节

看完完整代码后,可以回头重点检查三处。

第一处是数据声明。BannerItem / CategoryEntry / FlashSaleProduct这类结构把页面需要的字段提前摆出来,后面ForEach渲染时就不会到处临时拼数据。

第二处是状态更新。currentBanner / cartCount变化后,相关 UI 会自动刷新,这也是声明式 UI 写起来舒服的地方。你不用手动找某个控件改样式,只要把状态描述清楚。

第三处是容器嵌套。这个案例不是为了炫技才套RowColumnFlex,而是每一层都在解决具体排版问题。读代码时多问一句:这一层容器负责什么?如果答不上来,它可能就该被简化。

常见改造坑

最容易踩的坑,是把示例里的颜色、文案、尺寸都保留,然后只替换数据。这样页面能跑,但很难和自己的项目风格统一。

另一个坑是过度依赖固定宽高。固定宽高在演示里很方便,在真实设备上就未必稳。文本变长、屏幕变窄、系统字体变大,都会把问题暴露出来。

我一般会保留固定尺寸给图标、头像、按钮这类稳定元素;文本区域、列表区域、内容卡片尽量交给弹性布局处理。

写在最后

这个案例的价值不只是“有一份完整代码”。更重要的是你能从里面看到 ArkUI 页面的一条基本思路:数据先定义清楚,状态单独管理,布局按区域拆,交互只改必要状态。

按这个思路去写,页面复杂一点也不会马上失控。

http://www.jsqmd.com/news/1148165/

相关文章:

  • Document Loader与数据预处理
  • RFID固定资产管理系统在制造业的实践与应用
  • Cloudflare向AI公司下通牒,谷歌将面临痛苦抉择,AI行业数据格局或重塑!
  • 萨科微slkor2026年7月6日“每日芯闻”。国际芯闻:
  • 终极指南:Translumo - 免费高效的实时屏幕翻译神器,轻松突破语言障碍
  • Python进阶:迭代器(iterator)的原理与iter/next
  • NAS / 服务器断电数据丢失?UPS 配套 USB关机保护板,市电断电池低自动提示服务器/电脑关机
  • 【MATLAB】嵌入式实时调度与时序优化
  • 高压隔离技术:ISOM8710与PIC18LF25K80的工业应用
  • Xonsh:把 Python 和 Shell 融为一体的命令行体验
  • Three.js 网格地板教程
  • Transformer 模型参数量与计算量(FLOPs)关联分析:6PD 公式详解
  • PyTorch 2.2 与 TensorFlow 2.15 GPU 性能基准测试:矩阵运算速度对比分析
  • 电池连接器 > KH-CR1220-2
  • Linux文件系统inode机制深度解析:从`rm`删除到extundelete恢复的3层原理
  • 口碑爆棚!这些电动无轨龙门架销售厂家凭啥获得高评价?
  • Python基础数据操作与演示
  • DeMaVLA:面向可泛化形变物体的物理感知机器人基础模型
  • ServletContext 3.0+ 实战:5种获取方式与3类典型应用场景代码示例
  • 【小白也能轻松玩转龙虾】虾壳云一键部署办公增效工具,OpenClaw v2.7.9 自动整理文件资料(附最新安装包)
  • Sunshine游戏串流实战指南:从零搭建你的私人云游戏平台
  • 457. Java 反射 - 深度访问
  • AI Agent智能体开发公司推荐:2026年最新榜单
  • 气动系统是否可以完全替代液压系统?
  • 高压隔离技术:ISOM8710与PIC32MZ的工业应用解析
  • Ubuntu 22.04 LTS 软件安装:APT、Snap、Flatpak 3种方案性能与生态对比
  • 如何简单彻底清理Windows“此电脑“中的顽固图标:MyComputerManager完整指南
  • 2026.7.7最新财经播报综合分析
  • Horizon 8 企业CA证书实战:从OpenSSL生成到Connection Server部署的5个关键步骤
  • Kubernetes 探针实战:liveness、readiness、startup 到底怎么配