1、List容器组件:列表包含一系列相同宽度的列表项。
@Entry@Componentstruct ListTest { private data: number[] = [1, 2, 3, 4, 5, 6,] build() { Column() { //space:子组件主轴方向的间隔距离,默认为0 //initialIndex:初次加载时视口起始位置显示的item的索引值,默认为0 List({ space: 10, initialIndex: 0 }) { ForEach(this.data, (item) => { ListItem() { Text('第' + item+'个').width('100%').height(50) .fontSize(16).textAlign(TextAlign.Center) } }, item => item) } //listDirection:排列方向,Axis.Vertical为竖向、Axis.Horizontal为横向 .listDirection(Axis.Vertical) .width('100%') }.width('100%').height('100%') }
class Article { name: string; phone: string; constructor(name: string, phone: string) { this.name = name; this.phone = phone; }}@Entry@Componentstruct List2Test { //另外一种数据源的方式 @State articleList: Array<Article> = [ new Article('张三', '13839312311'), new Article('李四', '13839312312'), new Article('赵五', '13839312313'), ] build() { Column({ space: 5 }) { List() { ForEach(this.articleList, (item: Article) => { ListItem() { ArticleCard({ article: item }) .margin({ top: 20 }) } }, (item: Article) => item.name) } }.width('100%').height('100%') }}
@Componentstruct ArticleCard { article: Article; build() { Row() { //条目中放多个内容 Image($r('app.media.icon')) .width(80).height(80).margin({ right: 20 }) Column() { Text(this.article.name).fontSize(20).margin({ bottom: 8 }) Text(this.article.phone).fontSize(16).margin({ bottom: 8 }) } .alignItems(HorizontalAlign.Start) .width('80%').height('100%') }.padding(20).borderRadius(12) .backgroundColor(Color.Red) .height(120).width('100%').justifyContent(FlexAlign.SpaceBetween) }}