List
列表(List)是一种复杂容器,具备下列特点:
- 列表项(ListItem)数量过多超出屏幕后,会自动提供滚动功能。
- 列表项(ListItem)既可以纵向排列,也可以横向排列。
语法
List({ space: 10 }) {
ForEach([1, 2, 3, 4], item => {
ListItem() {
Text('ListItem')
}
})
}
.width('100%')
.listDirection(Axis.Vertical)
-
space:列表项间距。
-
ListItem:列表项。它本身不是一个容器,代表 List 内部的一个项,需要把各种布局组件(Text、Button 等)写在 ListItem 里。因为 ListItem 内部只能包含一个根组件,所以如果要写多个组件,需要将组件包到 Row 或 Colum 容器里。
ListItem() { Row() { ... } }
-
listDirection:列表方向,默认纵向。
Axis.Vertical // 纵向 Axis.Horizontal // 横向
示例代码
class Item {
name: string
image: ResourceStr
box_office: string
constructor(name: string, image: ResourceStr, box_office: string) {
this.name = name
this.image = image
this.box_office = box_office
}
}
@Entry
@Component
struct Index {
private items: Array<Item> = [
{ name: '热辣滚烫', image: $r('app.media.1'), box_office: '23.41亿' },
{ name: '飞驰人生2', image: $r('app.media.2'), box_office: '20.46亿' },
{ name: '熊出没·逆转时空', image: $r('app.media.3'), box_office: '11.82亿' },
{ name: '第二十条', image: $r('app.media.4'), box_office: '10.41亿' },
{ name: '我们一起摇太阳', image: $r('app.media.5'), box_office: '9618.7万' },
{ name: '红毯先生', image: $r('app.media.6'), box_office: '7884.5万' }
]
build() {
Column({ space: 8 }) {
Row() {
Text('2024春节档新片票房榜')
.fontSize(30)
.fontWeight(FontWeight.Bold)
}
List({ space: 8 }) {
ForEach(
this.items,
(item: Item) => {
ListItem() {
Row({ space: 8 }) {
Image(item.image)
.width(157)
.height(220)
Column() {
Text(item.name)
.fontSize(20)
.fontWeight(FontWeight.Bold)
Text(item.box_office)
.fontSize(18)
}
.height('100%')
.alignItems(HorizontalAlign.Start)
}
.width('100%')
.height(220)
}
}
)
}
.width('100%')
.height('100%')
}
.width('100%')
.height('100%')
.padding(8)
}
}
运行效果: