鸿蒙开发04界面渲染-三、滚动渲染

时间:2025-04-11 11:12:44

当和页面做滚动交互时,主要分为下拉刷新和上拉加载。

3.1 下拉刷新

当页面下拉时,应该刷新页面数据。

Refresh({
  refreshing: $$this.refreshing,
  builder: this.refreshContent
}){
  List(){
    ForEach(this.list, (item:number)=>{
      ListItem(){
        Row(){
          Text(item.toString())
        }.width('100%').padding(20)
        .border({
          width: {
            bottom: 1
          },
          color: Color.Gray
        })
      }
    })
  }
}.onRefreshing(()=>{
  setTimeout(()=>{
    this.list = Array(20).fill(Date.now())
    this.refreshing = false
  }, 1000)
})

Refresh组件:refreshing属性是指正在刷新状态的双向绑定,builder属性是指下拉刷新的显示页面组件(需要@Builder修饰符),onRefreshing是开始刷新事件函数。
builder代码如下:

@Builder
refreshContent(){
  Text('正在加载中...')
    .width('100%')
    .textAlign(TextAlign.Center)
    .backgroundColor(Color.Pink)
}

3.2 上拉加载

当页面在底部并上拉时,页面应该请求新数据并加载到页面中。

Refresh({
  refreshing: $$this.refreshing,
  builder: this.refreshContent
}){
  List(){
    ForEach(this.list, (item:number)=>{
      ListItem(){
        Row(){
          Text(item.toString())
        }.width('100%').padding(20)
        .border({
          width: {
            bottom: 1
          },
          color: Color.Gray
        })
      }
    })
  }
  .onScrollStart(()=>{
    // promptAction.showToast({message: '开始滚动'})
    this.isEnd = false
  })
  .onScrollStop(()=>{
    if (this.isEnd) {
      setTimeout(()=>{
        this.list.push(...Array(10).fill(Date.now()))
        promptAction.showToast({message: '已经添加10条数据'})
        this.scroller.scrollEdge(Edge.Bottom)
      }, 100)
    }
  })
  .onReachEnd(()=>{
    this.isEnd = true
  })
}.onRefreshing(()=>{
  setTimeout(()=>{
    this.list = Array(20).fill(Date.now())
    this.refreshing = false
  }, 1000)
})

上拉加载的时机:页面到底部,并且还在上拉刷新。就会加载数据到页面,并且页面定位到新加载数据处。
List组件:onScrollStart开始滚动事件函数,onScrollStop停止滚动事件函数,onReachEnd到达底部事件函数。