鸿蒙掌上驾考宝典应用开发13:List 列表组件——高性能长列表渲染
·
第13篇:List 列表组件——高性能长列表渲染
一、引言
List 是鸿蒙 ArkUI 中用于展示长列表的容器组件,支持高效的滚动渲染。DriverLicenseExam 项目在多个场景中使用 List 组件,包括视频列表、功能列表等。本文将详细解析 List 组件的使用和性能优化。
二、List 基本用法
2.1 水平视频列表
在 HomeView 中,List 用于展示水平滚动的视频列表:
// 考场必考项目讲解——视频列表
Column({ space: 12 }) {
Text('考场必考项目讲解')
.fontSize(16)
.fontColor($r('sys.color.font_primary'))
.width(CommonConstants.FULL_WIDTH)
.maxFontScale(1);
List({ space: 12 }) {
ForEach(this.videoList, (item: Video) => {
ListItem() {
Column({ space: 8 }) {
// 视频封面
RelativeContainer() {
Image(item.poster)
.width(CommonConstants.FULL_WIDTH)
.height(CommonConstants.FULL_HEIGHT);
Image($r('app.media.play_button'))
.width(24).height(24)
.alignRules({
bottom: { anchor: '__container__', align: VerticalAlign.Bottom },
right: { anchor: '__container__', align: HorizontalAlign.End }
})
.offset({ x: -8, y: -8 });
}
.height(80)
.width(CommonConstants.FULL_WIDTH)
.onClick(() => {
this.vm.navStack.pushPathByName('videoDetailView', item);
});
Text(item.name)
.fontSize(14)
.fontColor($r('sys.color.font_secondary'))
.width(CommonConstants.FULL_WIDTH)
.maxFontScale(1);
}
.width(104);
}
}, (item: Video) => JSON.stringify(item));
}
.layoutWeight(1)
.listDirection(Axis.Horizontal) // 水平方向
.scrollBar(BarState.Off); // 隐藏滚动条
}
2.2 垂直功能列表
在 MineView 中,List 用于展示垂直排列的功能菜单:
// 我的页面——功能列表
List() {
ForEach(COMMON_SERVICE, (item: MinePageCommonService) => {
ListItem() {
Column() {
if (item.label === '意见反馈') {
this.Feedback(item);
} else {
this.FunctionItem(item);
}
}
.width(CommonConstants.FULL_PERCENT)
.height(46);
}
}, (item: MinePageCommonService) => {
return JSON.stringify(item.label);
});
}
.backgroundColor($r('sys.color.comp_background_primary'))
.divider({
strokeWidth: 0.5,
color: $r('sys.color.comp_divider'),
startMargin: 12,
endMargin: 12
})
.borderRadius(16)
.edgeEffect(EdgeEffect.Spring, { alwaysEnabled: true });
三、List 核心属性
3.1 方向控制
// 水平方向列表
List({ space: 12 })
.listDirection(Axis.Horizontal)
// 垂直方向列表(默认)
List({ space: 12 })
.listDirection(Axis.Vertical)
3.2 分割线配置
List()
.divider({
strokeWidth: 0.5, // 线宽
color: $r('sys.color.comp_divider'), // 颜色
startMargin: 12, // 起始缩进
endMargin: 12 // 结束缩进
});
3.3 边缘效果
List()
.edgeEffect(EdgeEffect.Spring, { alwaysEnabled: true });
// 弹簧效果,始终启用
四、ForEach 的 key 生成
4.1 key 的重要性
// 使用唯一标识作为 key
ForEach(this.videoList, (item: Video) => {
ListItem() { ... }
}, (item: Video) => JSON.stringify(item)); // 将整个 item 序列化作为 key
// 更好的做法:使用唯一 ID
ForEach(this.videoList, (item: Video) => {
ListItem() { ... }
}, (item: Video) => item.id);
五、总结
List 组件提供了高效的列表渲染能力,支持水平和垂直方向、分割线、边缘效果等特性。搭配 ForEach 使用时,合理的 key 生成策略可以显著提升列表渲染性能。
关键源码文件:
products/entry/src/main/ets/pages/home/HomeView.ets— 水平视频列表products/entry/src/main/ets/pages/mine/MineView.ets— 垂直功能列表
更多推荐



所有评论(0)