使用onSizeChange获取变化组件高度,修改目标容器的高度变量,实现组件与变化组件相同高度的效果。
@Component
export struct TimeLineView {
// 动态控制组件高度
@State heightNumber: Length = '100%';
// 编号
code: string = '';
// 内容存储
@State service: Array<string> = [];
build() {
Column() {
Row() {
Column() {
Image($r('app.media.startIcon'))
.width(30)
.height(30)
.margin({ top: 10 })
.objectFit(ImageFit.Contain);
Progress({ value: 50, type: ProgressType.Linear })
.width(10)
.layoutWeight(1)
.color('#0A59F7');
}
.height(this.heightNumber)
.justifyContent(FlexAlign.Start)
.alignItems(HorizontalAlign.Center);
Column() {
Text('步骤' + this.code)
.fontColor(Color.Black)
.fontSize(24)
.height(50);
ForEach(this.service, (item: string) => {
Text(item)
.margin({ top: 6, left: 10, right: 10 })
.fontSize(18);
});
Blank().height(6);
}
.margin({ left: 10 })
.width('80%')
.alignItems(HorizontalAlign.Start)
.justifyContent(FlexAlign.Start)
.onSizeChange((oldValue, newValue) => {
console.info(`oldValue: ${oldValue}, newValue: ${newValue}`);
// 根据内容区高度控制进度条高度
this.heightNumber = newValue.height ?? this.heightNumber;
});
};
}
.width('100%')
.backgroundColor(Color.White);
}
}
@Entry
struct Index {
// 模拟数据
one: Array<string> = ['流程-1', '流程-2'];
two: Array<string> = ['流程-3', '流程-4,模拟长段文字效果---------------'];
three: Array<string> = ['流程-5', '流程-6', '流程-7', '流程-8'];
build() {
Column() {
TimeLineView({ code: '一', service: this.one });
TimeLineView({ code: '二', service: this.two });
TimeLineView({ code: '三', service: this.three });
}
.padding({
top: 10,
left: 5,
right: 5,
bottom: 10
})
.width('90%')
.backgroundColor(Color.White)
.borderRadius(15);
}
} Q:是否还有其他可以获取组件高度的接口?
A:有,除上述组件尺寸变化事件onSizeChange外,还有组件区域变化事件和组件可见区域变化事件,但响应的场景不同,获取的信息也不同。建议使用组件尺寸变化事件,仅响应尺寸变化事件。