目录

Scroll容器嵌套RelativeContainer组件时无法滚动

问题现象

Scroll组件中嵌套RelativeContainer组件时,Scroll组件无法滚动。

问题示例代码如下:

import { window } from '@kit.ArkUI';

@Entry
@Component
struct Index {
  scroller: Scroller = new Scroller();

  aboutToAppear(): void {
    window.getLastWindow(this.getUIContext().getHostContext(), (err, data) => {
      data?.setWindowLayoutFullScreen(true); // 设置沉浸式布局,与知识内容无关仅为全屏展示效果
    });
  }

  build() {
    Scroll(this.scroller) {
      RelativeContainer() {
        Column({ space: 10 }) {
          Text('组件1')
            .fontColor(Color.White)
            .width('90%')
            .height('90%')
            .borderRadius(25)
            .textAlign(TextAlign.Center)
            .backgroundColor('#0a59f7');
          Text('组件2')
            .fontColor(Color.White)
            .width('90%')
            .height('90%')
            .borderRadius(25)
            .textAlign(TextAlign.Center)
            .backgroundColor('#0a59f7');
        }
        .width('100%');
      }
    }
    .width('100%')
    .height('100%');
  }
}

效果预览

背景知识

问题定位

RelativeContainer组件的默认高度是根据其父容器的高度确定。如果RelativeContainer组件没有设置具体的高度值,RelativeContainer组件会自动继承父组件的高度,而不是子组件高度。

由此可见,当Scroll组件的子组件是RelativeContainer组件,且RelativeContainer组件未设置高于Scroll组件的高度时,会违反Scroll组件的子组件总高度必须大于Scroll组件高度的滚动条件,导致无法滚动。

RelativeContainer组件的width属性、height属性参数设置"auto"时,表示RelativeContainer组件宽度和高度自适应子组件的宽度和高度。

分析结论

Scroll组件中嵌套RelativeContainer组件时,Scroll组件无法滚动的原因是:

RelativeContainer组件默认继承Scroll组件的高度,导致RelativeContainer组件高度无法超过Scroll组件高度,进而导致Scroll组件无法滚动。

修改建议

由于方案二、方案三会更改布局,推荐使用方案一。