List组件
List 组件是开发app中非常常见的组件,主要是制作页面的滚动,用来展示列表等。
1.分组展示
List组件作为顶级容器,ListltemGroup作为容器,Listltem作为List或者ListltemGroup的子组件
ListltenGroup(参数){}.属性()
header\footer\space是ListltemGroup的属性
ListltemGroupd的属性和list是一样的
{
strokeWidth: Length,
color?: ResourceColor,
startMargin?: Length,
endMargin?: Length
} | null
List() {
ListItemGroup({
ListItem() {
}
}
2.数据格式抽取演示
interface iGroup {
letter: string
list: string[]
}
@Entry
@Component
struct Index {
// 1. 数据定义
groups: iGroup[] = [
{ letter: 'A', list: ['阿猫', '阿狗'] },
{ letter: 'B', list: ['白兔', '白虎'] }
]
@Builder
headBuilder(letter: string) {
Text(letter)
.fontWeight(900)
.fontColor(Color.Red)
.fontSize(25)
.padding(10)
}
@Builder
footerBuilder() {
Text('底部')
.fontWeight(900)
.fontColor(Color.Green)
.fontSize(25)
.padding(10)
}
build() {
Column() {
List() {
// 2. 遍历数组生成的是ListItemGroup分组
ForEach(this.groups, (item: iGroup) => {
ListItemGroup({
header: this.headBuilder(item.letter),
// footer: this.footerBuilder,
// space:20
}) {
ForEach(item.list,(text:string)=>{
ListItem() {
Text(text)
.fontSize(30)
}
})
}
})
}
// .divider({strokeWidth:2,color:Color.Green})
}
.height('100%')
.width('100%')
.backgroundColor(Color.Pink)
}
}
3.粘性标题
通过List组件的sticky属性,进行操作
.sticky(StickyStyle.None) // 不吸附 默认值 .sticky(StickyStyle.Header) // 头部吸附 .sticky(StickyStyle. Footer) // 底部吸附,如果有的话
4.控制滚动
如果列表很长,需要快速滚动到列表底部或返回列表顶部,就可以使用代码来控制滚动
// 2. 设置给 List 组件
List({ space: 20, scroller: this.listScroller }) {
// ...
listScroller: ListScroller = new ListScroller()
// 1. 创建控制器(ListScroller)对象
}
Button() {
// ...
}
.onClick(() => {
// 3. 调用控制器对象的方法,实现滚动
this.listScroller.scrollToIndex(0)
})
5.事件
onScroll 此事件计算索引值的功能
List(){
// ...
}
.onScrollIndex((index: number) => {//计算索引值
console.log('index:', index)
})