HarmonyOS 鸿蒙Next 组件加入Grid()组件报错 here should have a root container component

HarmonyOS 鸿蒙Next 组件加入Grid()组件报错 here should have a root container component

@Entry @Component struct Index { @State message: string = ‘字母消消乐’ private alphabets: Array<string> = [‘A’, ‘A’, ‘B’, ‘B’, ‘C’, ‘C’, ‘D’, ‘D’]

build() { // 这里标红线 Column() { Text(this.message) .fontSize(50) .fontWeight(FontWeight.Bold) } .width(‘100%’)

Column({ space: 4 }) {
  Grid() {
    ForEach(this.alphabets, (alphabet: string) => {
      GridItem() {
        Text(alphabet)
          .fontSize(16)
          .backgroundColor(0xF9CF93)
          .width('100%')
          .height('100%')
          .textAlign(TextAlign.Center)
      }
    }, alphabet => alphabet)
  }
  .columnsTemplate('1fr 1fr 1fr 1fr')
  .rowsTemplate('1fr 1fr')
  .columnsGap(10)
  .rowsGap(10)
  .width('90%')
  .backgroundColor(0xFAEEE0)
  .height(300)
}

} }


更多关于HarmonyOS 鸿蒙Next 组件加入Grid()组件报错 here should have a root container component的实战教程也可以访问 https://www.itying.com/category-93-b0.html

4 回复

不是报Grid()组件,而是你的代码结构导致的,build() 里面只能包含一个根容器,你写了两个Column(),正确代码

build() {   // 这里标红线    
 Column({ space: 4 }) {
    Text(this.message)
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
    Grid() {
        ForEach(this.alphabets, (alphabet: string) => {
            GridItem() {
                Text(alphabet)
                    .fontSize(16)
                    .backgroundColor(0xF9CF93)
                    .width('100%')
                    .height('100%')
                    .textAlign(TextAlign.Center)
            }
        }, alphabet => alphabet)
    }
    .columnsTemplate('1fr 1fr 1fr 1fr')
    .rowsTemplate('1fr 1fr')
    .columnsGap(10)
    .rowsGap(10)
    .width('90%')
    .backgroundColor(0xFAEEE0)
    .height(300)
}

更多关于HarmonyOS 鸿蒙Next 组件加入Grid()组件报错 here should have a root container component的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


感谢,已经解决了,洗涤液大佬们,

在build()里增加一个Column,将现有的2个Column都放入增加的Column中

在HarmonyOS鸿蒙Next中,Grid组件的使用需要遵循其特定的布局规则。报错信息“here should have a root container component”表明Grid组件需要一个根容器组件来包裹。Grid组件通常需要在<Column><Row><Stack>等容器组件中使用,以确保布局的正确性。

例如,正确的使用方式如下:

@Entry
@Component
struct GridExample {
  build() {
    Column() {
      Grid() {
        // Grid items here
      }
    }
  }
}

如果直接使用Grid组件而没有将其放在根容器组件中,系统会抛出上述错误。确保Grid组件被适当的容器组件包裹即可解决该问题。

回到顶部