HarmonyOS 如何判断List中的item是否可见以及如何更新List中的某一个item?

如何判断List中的item是否可见,可以获取到当前显示的第一个item的是属于第几个么

如何更新List中的某一个item,我有一个list组件 其中的数据为PostData,假设第三个发生了改变,我应该如何更新

阅读 515
1 个回答

第一个可以通过onScrollIndex监听,可以参考demo:

@Entry
@Component
struct ListExample {
  private arr: (number | string)[] = [0, '概览', '周边', 3, 4, '房源', 6, 7, '小区', 9, 10, 11, 12, 13, 14, 15]
  private tabArr: string[] = ['概览', '周边', '房源', '小区']
  @State currentIndex: number = 0

  build() {
    Column() {
      Row() {
        ForEach(this.tabArr, (item: string, index: number) => {
          Text(item)
            .fontColor(this.currentIndex === index ? Color.Blue : '')
        })
      }
      .width('100%')
      .padding({ left: 20 })
      .alignItems(VerticalAlign.Top)

      List({ space: 20, initialIndex: 0 }) {
        ForEach(this.arr, (item: number) => {
          ListItem() {
            Text('' + item)
              .width('100%')
              .height(100)
              .fontSize(16)
              .textAlign(TextAlign.Center)
              .borderRadius(10)
              .backgroundColor(0xFFFFFF)
          }
        }, (item: string) => item)
      }
      .listDirection(Axis.Vertical) // 排列方向
      .scrollBar(BarState.Off)
      .friction(0.6)
      .divider({ strokeWidth: 2, color: 0xFFFFFF, startMargin: 20, endMargin: 20 }) // 每行之间的分界线
      .edgeEffect(EdgeEffect.Spring) // 边缘效果设置为Spring
      .onScrollIndex((firstIndex: number, lastIndex: number, centerIndex: number) => {
        console.info('first' + firstIndex)
        console.info('last' + lastIndex)
        console.info('center' + centerIndex)
        if (firstIndex == 1) {
          this.currentIndex = 0
        } else if (firstIndex == 2) {
          this.currentIndex = 1
        } else if (firstIndex == 5) {
          this.currentIndex = 2
        } else if (firstIndex == 8) {
          this.currentIndex = 3
        }
      })
      .width('90%')
    }
    .width('100%')
    .height('100%')
    .backgroundColor(0xDCDCDC)
    .padding({ top: 5 })
  }
}

第二个更新数组对象内的属性可以使用@Observed,参考:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/arkts-observed-and-objectlink-V5\#%E5%AF%B9%E8%B1%A1%E6%95%B0%E7%BB%84

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进