【HarmonyOS 5.0.0 或以上】构建加载骨架屏 Skeleton:内容加载占位 / 图文块骨架 / 自定义动画样式

🎯 目标

封装一个通用骨架屏组件 CommonSkeleton,适用于:

  • 内容加载前的视觉占位

  • 图文布局预占(如头像 + 标题 + 文本)

  • 支持矩形 / 圆形 / 多行骨架块组合

  • 动画样式自定义(闪烁 / 渐变 / 呼吸)

  • 可用于页面、卡片、表单加载等待状态


🧱 样式示意

⬤  ▬▬▬▬▬▬▬▬▬▬
   ▬▬▬▬▬▬▬▬▬▬
   ▬▬▬▬▬▬▬▬      ← 模拟内容加载中占位图

🧰 组件实现:CommonSkeleton.ets

@Component
export struct CommonSkeleton {
  @Prop rows: number = 3
  @Prop avatar: boolean = false
  @Prop avatarSize: number = 40
  @Prop animate: boolean = true
  @Prop radius: number = 4
  @Prop lineHeight: number = 12
  @Prop lineSpacing: number = 8

  build() {
    Row()
      .alignItems(VerticalAlign.Top)
      .padding(12) {
      if (this.avatar) {
        Circle()
          .width(this.avatarSize)
          .height(this.avatarSize)
          .backgroundColor('#e0e0e0')
          .animate(this.animate ? this.shimmer() : null)
      }

      Column()
        .margin({ left: this.avatar ? 12 : 0 })
        .flexGrow(1) {
        ForEach(new Array(this.rows), (_, i) => {
          Blank()
            .width('100%')
            .height(this.lineHeight)
            .backgroundColor('#e0e0e0')
            .borderRadius(this.radius)
            .margin({ bottom: i === this.rows - 1 ? 0 : this.lineSpacing })
            .animate(this.animate ? this.shimmer() : null)
        })
      }
    }
  }

  private shimmer(): AnimateOptions {
    return {
      duration: 1200,
      iterations: -1,
      curve: Curve.Linear,
      onFrame: (progress: number) => {
        return {
          backgroundColor: this.gradientColor(progress)
        }
      }
    }
  }

  private gradientColor(progress: number): string {
    // 模拟灰色闪烁动画
    const value = Math.floor(224 + Math.sin(progress * 2 * Math.PI) * 16)
    return `rgb(${value}, ${value}, ${value})`
  }
}

📦 使用示例

@Entry
@Component
struct DemoSkeleton {
  @State loading: boolean = true
  @State data: { title: string, content: string } | null = null

  aboutToAppear() {
    setTimeout(() => {
      this.data = {
        title: 'HarmonyOS 组件开发实践',
        content: '本课程带你从零实现常用 UI 组件...'
      }
      this.loading = false
    }, 2000)
  }

  build() {
    if (this.loading) {
      CommonSkeleton({ avatar: true, rows: 3 })
    } else {
      Row().padding(12) {
        Circle().width(40).height(40).backgroundColor('#ddd')
        Column().margin({ left: 12 }) {
          Text(this.data!.title).fontSize(16).fontWeight(FontWeight.Bold)
          Text(this.data!.content).fontSize(14).fontColor('#666').margin({ top: 4 })
        }
      }
    }
  }
}

✨ 可扩展能力建议

功能说明
自定义骨架布局提供 slot 插槽或 schema 配置指定骨架形状
页面级骨架包裹整页组件外包裹 skeleton loading 层结构
动画样式支持可选择 shimmer、呼吸、闪烁、流光等多种动画样式
支持骨架屏状态切换与接口 loading 状态联动(配合请求封装)

📘 下一篇预告

第37篇:【HarmonyOS 5.0.0 或以上】构建可排序列表组件 SortableList:支持拖动排序 / 动画反馈 / 数据同步

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值