zIndex属性能够设置组件的堆叠顺序,因此可以通过设置zIndex属性实现抽屉层级效果,而visibility属性能够控制组件的显示与隐藏,因此可以通过设定状态变量,通过状态变量控制visibility属性从而控制组件的显隐,配合animation添加过渡动画,即可实现抽屉的弹出效果,具体实现如下:
完整代码如下:
@Entry
@Component
struct DrawerDemo {
@Provide('panelHeightFirst') panelHeightFirst: string = '0'; // 控制第一层抽屉高度。
@Provide('panelHeightSecond') panelHeightSecond: string = '0'; // 控制第二层抽屉高度。
@Provide('level') level: number = 0; // 控制遮罩层级显示。
build() {
Stack({ alignContent: Alignment.Bottom }) {
Column() {
Button('弹起')
.margin({ top: 8 })
.onClick(() => {
// 判断当前是否已弹出,切换状态。
if (this.panelHeightFirst === '0') {
this.panelHeightFirst = '40%';
this.level = 2;
} else {
this.panelHeightFirst = '0';
this.level = 0;
}
});
}
.height('100%')
.width('100%')
.backgroundColor('#F1F3F5')
.zIndex(1)
.justifyContent(FlexAlign.Center);
Column() {
}
.height('100%')
.width('100%')
.backgroundColor(Color.Black)
.opacity(0.10)
.zIndex(this.level)
.onClick(() => {
// 点击遮罩时关闭所有抽屉。
this.panelHeightFirst = '0';
this.panelHeightSecond = '0';
this.level = 0;
});
CustomAlertFirst()
.height(this.panelHeightFirst)
.visibility(this.panelHeightFirst === '0' ? Visibility.Hidden : Visibility.Visible)
.animation({ duration: 300 })
.zIndex(2);
CustomAlertSecond()
.height(this.panelHeightSecond)
.visibility(this.panelHeightSecond === '0' ? Visibility.Hidden : Visibility.Visible)
.animation({ duration: 300 })
.zIndex(3);
};
}
}
// 第一层抽屉组件。
@Component
struct CustomAlertFirst {
@Consume('panelHeightSecond') panelHeightSecond: string;
@Consume('level') level: number;
build() {
Column() {
Button('再弹/消失')
.margin({ top: 8 })
.onClick(() => {
if (this.panelHeightSecond === '0') {
this.panelHeightSecond = '20%';
this.level = 2;
} else {
this.panelHeightSecond = '0';
this.level = 2;
}
});
}
.width('100%')
.height('100%')
.borderRadius({ topLeft: 15, topRight: 15 })
.backgroundColor('#F1F3F5');
}
}
// 第二层抽屉组件。
@Component
struct CustomAlertSecond {
@Consume('panelHeightSecond') panelHeightSecond: string;
@Consume('level') level: number;
build() {
Column() {
Button('OK')
.margin({ top: 8 })
.onClick(() => {
this.panelHeightSecond = '0';
this.level = 2;
});
}
.width('100%')
.height('100%')
.borderRadius({ topLeft: 15, topRight: 15 })
.backgroundColor('#ffffffff');
}
}