网格布局高度自适应?

grid布局的文档中说:“如果Grid组件设置了宽高属性,则其尺寸为设置值。如果没有设置宽高属性,Grid组件的尺寸默认适应其父组件的尺寸”,目前有个九宫格图片展示,我想使用grid来实现(图片可能是5-9张),我设置了三列columnsTemplate(‘1fr 1fr 1fr’),图片设置了aspectRatio(1),但是这个Grid的高度不设置的话,高度占满屏幕,影响到下面的展示,如果设置高度,应该如何设置。期望grid高度能根据内容自适应。

阅读 574
1 个回答

grid的width设为100%,图片设置aspectRatio(1)即可

@Entry
@Component
struct Page_0094 {
  private children: string[] = ['1', '2', '3', '4', '5', '6', '7', '8', '9']

  build() {
    Column({ space: 20 }) {
      Grid() {
        ForEach(this.children, (item: string) => {
          GridItem() {
            Text(item)
              .backgroundColor(Color.Gray)
              .fontSize(40)
              .fontColor(Color.White)
              .width('100%')
              .aspectRatio(1)
              .textAlign(TextAlign.Center)
          }
        }, (item: string) => item)
      }
      .width('100%')
      // .height(400)
      .columnsTemplate('1fr 1fr 1fr')
      .maxCount(3)
      .columnsGap(2)
      .rowsGap(2)
      .backgroundColor(Color.Pink)
    }
  }
}

https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/web-nested-scrolling-0000001774120278

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