布局组件Row、Column、Stack、Flex、List、Swiper等均为可容纳子组件的容器组件。
根据组件宽高的数值来判断容器内部是否有内容,由于计算精度可能导致的误差,所以设置比较范围而不是判断是否为零。
@Entry @Component struct PageMargin { @State dataSource: string[] = []; // 数据源 @State content: boolean = false; // 自行保存容器内部状态 @State rowWidth: number = 0; // 状态变量,保存容器组件的宽度 build() { Column({ space: 16 }) { // 方案一 Column() { // 当前Column中无组件 } .onAreaChange((oldValue: Area, newValue: Area) => { this.rowWidth = newValue.width as number; console.info(`rowWidth: ${this.rowWidth}`); }) .backgroundColor('#0a59f7') .margin(this.rowWidth <= 1 ? '0' : '20vp'); // 依据宽度控制margin // 方案二 Column({ space: 16 }) { Button('toggle') .backgroundColor('#0a59f7') .onClick(() => { this.content = !this.content; }); if (this.content) { Text('hello world'); } } .margin(this.content === true ? '20vp' : '0'); // 方案三 Button('add dataSource') .backgroundColor('#0a59f7') .onClick(() => { this.dataSource.push('数据'); }); List() { ForEach(this.dataSource, (item: string, index: number) => { ListItem() { Text(item) .onClick(() => { console.info(`index: ${index}`); }); }; }, (item: string, index) => item + index); } .padding(8) .backgroundColor('#f1f3f5') .borderRadius(5) .margin(this.dataSource.length === 0 ? '0' : '20vp'); } .padding(16) .height('100%') .width('100%'); } }