通过计算展示的行数rowCount,根据rowCount得出GridHeight、GridRowsTemplate。参考demo:@Entry @Component struct ABPage { @State message: string = 'Hello World'; private controller: TextInputController = new TextInputController() @State simpleList: Array<string> = ['one', 'two', 'three', 'one', 'two', 'three','one', 'two', 'three', 'one', 'two',]; getCategoryRowCount() { return Math.ceil(this.simpleList.length / 3); } getCategoryRowTmpl() { const count = this.getCategoryRowCount(); const arr: string[] = new Array(count || 1).fill('1fr'); console.log('tmpl ', arr.join(' ')) return arr.join(' '); } getCategoryViewHeight() { return `${50 * this.getCategoryRowCount()}vp`; } build() { Column() { Column() { Grid() { ForEach(this.simpleList, (item: string) => { this.gridItemBuilder(item) }) } .height(this.getCategoryViewHeight()) .rowsTemplate(this.getCategoryRowTmpl()) .columnsTemplate('1fr 1fr 1fr ') } // .height("15%") .backgroundColor('#ff02194c') .justifyContent(FlexAlign.SpaceEvenly) Column() { List() { ForEach(this.simpleList, (item: string) => { this.gridItemBuilder(item) }) } } .backgroundColor('#ffcff10c') .height("100%") } .width('94%') .height('80%') .borderRadius(10) .backgroundColor('#ff8f1616') .justifyContent(FlexAlign.Start) .margin({ top: '10%', left: '3%', right: '3%',bottom:'10%' }) } @Builder gridItemBuilder(content: string) { GridItem() { Column() { Text(content) .fontSize(15) } .justifyContent(FlexAlign.Center) .borderRadius(10) .backgroundColor('#ffeabe4f') .height('25vp') .width('100%') .margin({ top: '5vp' }) .onClick(() => { }) } } }
通过计算展示的行数rowCount,根据rowCount得出GridHeight、GridRowsTemplate。参考demo: