🎯 目标
封装一个通用骨架屏组件 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:支持拖动排序 / 动画反馈 / 数据同步