#鸿蒙通关秘籍#在 HarmonyOS Next 中如何通过下拉刷新组件实现上次更新时间显示?

HarmonyOS
20h前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
hm673ff0f70d919

可以在自定义的刷新组件中,通过获取当前时间戳,实现上次更新时间的显示。步骤如下:

@Entry
@Component
struct PullRefresh {
  @State isRefreshing: boolean = false;
  @State promptText: string = '';
  @State refreshStatus: number = 0;
  @State list: number[] = [];
  @State lastTime: string = this.getDateTime();

  aboutToAppear(): void {
    this.getList();
  }

  getList() {
    setTimeout(() => {
      for (let i = 0; i < 20; i++) {
        this.list.push(i);
      }
      this.isRefreshing = false;
    }, 1000);
  }

  getDateTime() {
    let date = new Date();
    let month = (date.getMonth() + 1).toString().padStart(2, '0');
    let day = date.getDate().toString().padStart(2, '0');
    let hour = date.getHours().toString().padStart(2, '0');
    let minus = date.getMinutes().toString().padStart(2, '0');
    return `${month}-${day} ${hour}:${minus}`;
  }

  @Builder customRefreshComponent() {
    Row({space:15}){
      Column({space:3}){
        Text(this.promptText).fontSize(14).fontColor('#666').lineHeight(21);
        Text(`上次更新 ${this.lastTime}`).fontSize(11).fontColor('#808080');
      }
    }.width('100%').constraintSize({minHeight:50}).justifyContent(FlexAlign.Center);
  }

  build() {
    Refresh({ refreshing: $$this.isRefreshing, builder:this.customRefreshComponent() }) {
      List({space:20}){
        ForEach(this.list, (item: number) => {
          ListItem(){
            Text(item.toString());
          }
          .width('100%')
          .height(90)
          .backgroundColor('#fff')
          .borderRadius(10);
        }, (item: number) => item.toString());
      }
      .height('100%')
      .width('100%')
      .padding(20)
      .backgroundColor('#f2f2f2');
    }
    .refreshOffset(100)
    .onStateChange((state) => {
      this.refreshStatus = state;
      switch (state) {
        case RefreshStatus.Drag:
          this.promptText = '下拉可以刷新';
          break;
        case RefreshStatus.OverDrag:
          this.promptText = '释放立即刷新';
          break;
        case RefreshStatus.Refresh:
          this.promptText = "正在刷新...";
          this.getList();
          break;
        case RefreshStatus.Done:
          this.lastTime = this.getDateTime();
          break;
      }
    });
  }
}

通过回调函数中 RefreshStatus.Done 更新 lastTime 字段,即可在界面上展示上次更新时间。

分享
微博
QQ
微信
回复
19h前
相关问题