鸿蒙next中,如何解决滚动容器嵌套的滚动顺序问题

177 阅读1分钟

话不多说,直接先上代码

@Entry
@Component
struct Index {
  build() {
    List() {
      ListItem() {
        List() {
          ForEach(Array.from({ length: 20 }), (item: string, index: number) => {
            ListItem() {
              Text(index + "")
                .textAlign(TextAlign.Center)
                .fontSize(20)
            }
            .padding(10)
          })
        }
        .nestedScroll({
          scrollBackward: NestedScrollMode.SELF_FIRST,
          scrollForward: NestedScrollMode.SELF_FIRST
        })
        .backgroundColor(Color.Pink)
      }
      .height('50%')

      ListItem() {
        List() {
          ForEach(Array.from({ length: 30 }), (item: string, index: number) => {
            ListItem() {
              Text(index + "")
                .textAlign(TextAlign.Center)
                .fontSize(20)
            }
            .padding(10)
          })
        }
        .nestedScroll({
          scrollBackward: NestedScrollMode.SELF_FIRST,
          scrollForward: NestedScrollMode.SELF_FIRST
        })
        .backgroundColor(Color.Green)
      }
      .height('80%')

      ListItem() {
        Column() {
          ForEach(Array.from({ length: 10 }), (item: string, index: number) => {
            Text('这是隐藏的内容' + index + 1)
          })
        }
      }
    }
    .nestedScroll({
      scrollBackward: NestedScrollMode.SELF_ONLY,
      scrollForward: NestedScrollMode.SELF_ONLY
    })
    .padding(10)
    .width("100%")
    .height('100%')
    .backgroundColor("#f5f5f5")
  }
}

image.png

image.png

在开发中,我们可能会碰到一个场景,有一个滚动列表,里面有很多个其他的滚动容器。这样就形成了滚动嵌套,滚动的时候会发生冲突,不知道哪个先滚,哪个后滚。

此时我们可以利用nestedScroll属性。这个属性在大部分滚动容器中都有,就是用来解决这个问题的。scrollBackward这个是下滚的时候的优先级,另一个是上滚的时候的优先级。当我们把优先级都设置为,self_only,则为自身先滚动后,就可以实现上面的效果啦~