问题1:Flex方向为Column时,默认高度会撑满Flex的父容器。如何让Flex的高度自适应子组件的高度?
问题2:Flex方向为Row时,默认宽度会撑满Flex的父容器,如何让Flex宽度自适应子组件的宽度?
问题1效果预览:

问题2效果预览:

问题1:Flex方向为Column,可以将Flex组件高度设置为auto,使Flex自适应子组件布局的高度。
@Entry
@Component
struct FlexExample1 {
build() {
Column({ space: 10 }) {
Text('Flex方向为Column');
Flex({ direction: FlexDirection.Column }) {
Text('Flex的子组件\nHello World!')
.backgroundColor('#330a59f7')
.textAlign(TextAlign.Center)
.borderRadius(30)
.padding(20);
}
.backgroundColor('#f1f3f5')
.height('auto');
}
.height('100%')
.width('100%');
}
} 效果预览:

问题2:Flex方向为Row时同理,设置宽度为auto,使Flex自适应子组件布局的宽度。
@Entry
@Component
struct FlexExample2 {
build() {
Column({ space: 10 }) {
Text('Flex方向为Row');
Flex({ direction: FlexDirection.Row }) {
Text('Flex的子组件\nHello World!')
.backgroundColor('#330a59f7')
.textAlign(TextAlign.Center)
.borderRadius(30)
.padding(20);
}
.backgroundColor('#f1f3f5')
.width('auto');
}
.height('100%')
.width('100%');
}
} 效果预览:

问题1:Flex方向为Column时,通过onSizeChange获取子组件高度,设置Flex高度。
@Entry
@Component
struct FlexExample3 {
@State flexHeight: number | string = '100%'; // 默认情况主轴占满
build() {
Column({ space: 10 }) {
Text('Flex方向为Column');
Flex({ direction: FlexDirection.Column }) {
Text('Flex的子组件\nHello World!')
.backgroundColor('#330a59f7')
.textAlign(TextAlign.Center)
.borderRadius(30)
.padding(20)
.onSizeChange((oldSize, newSize) => { // 也可以使用onAreaChange
this.flexHeight = newSize.height as number; // 获取子组件高
});
}
.backgroundColor('#f1f3f5')
.height(this.flexHeight);
}
.height('100%')
.width('100%');
}
} 效果预览:

问题2:Flex方向为Row时,通过onSizeChange获取子组件宽度,设置Flex宽度。
@Entry
@Component
struct FlexExample4 {
@State flexWidth: number | string = '100%'; // 默认情况主轴占满
build() {
Column({ space: 10 }) {
Text('Flex方向为Row');
Flex({ direction: FlexDirection.Row }) {
Text('Flex的子组件\nHello World!')
.backgroundColor('#330a59f7')
.textAlign(TextAlign.Center)
.borderRadius(30)
.padding(20)
.onSizeChange((oldSize, newSize) => { // 也可以使用onAreaChange
this.flexWidth = newSize.width as number; // 获取子组件宽
});
}
.backgroundColor('#f1f3f5')
.width(this.flexWidth);
}
.height('100%')
.width('100%');
}
} 效果预览:
