在HarmonyOS NEXT开发中有回调函数的全局自定义弹窗代码例子?
在HarmonyOS NEXT开发中,你可以使用ArkUI(使用JS或eTS框架)来实现全局自定义弹窗,并结合回调函数来处理用户交互。以下是一个使用eTS框架的简单示例,展示了如何创建一个带有回调函数的全局自定义弹窗。
### 自定义弹窗组件(MyDialog.ets)
import { Component, ref } from '@ohos.arkui';
@Entry
@Component
struct MyDialog {
@State isVisible: boolean = false;
@State result: string = '';
private callback: (result: string) => void = () => {};
build() {
Column() {
if (this.isVisible) {
Dialog() {
Column() {
Text('This is a custom dialog')
.fontSize(20)
.textAlign(TextAlign.Center);
Button('Confirm')
.onClick(() => {
this.callback('Confirmed');
this.isVisible = false;
});
Button('Cancel')
.onClick(() => {
this.callback('Cancelled');
this.isVisible = false;
});
}.padding(20)
}.width('100%').height('auto').margin(20);
}
}
}
showDialog(callback: (result: string) => void) {
this.callback = callback;
this.isVisible = true;
}
}
### 使用自定义弹窗的主组件(MainAbility.ets)
import { Component, ref } from '@ohos.arkui';
import MyDialog from './MyDialog';
@Entry
@Component
struct MainAbility {
@State dialog: MyDialog | null = null;
aboutToAppear() {
this.dialog = new MyDialog();
}
showCustomDialog() {
if (this.dialog) {
this.dialog.showDialog((result) => {
console.log('Dialog result:', result);
});
}
}
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button('Show Dialog')
.onClick(() => this.showCustomDialog())
.width('80%')
.height(50)
.backgroundColor(Color.Blue)
.textColor(Color.White)
.textFont({ fontSize: 18 })
.margin({ top: 50 });
}
}
}
### 解释
1. **MyDialog.ets**:定义了一个自定义弹窗组件,包含一个`Dialog`,其中有“Confirm”和“Cancel”两个按钮。点击按钮时会调用传入的回调函数,并传递相应的结果。
2. **MainAbility.ets**:在主组件中,通过实例化`MyDialog`组件来显示弹窗。`showCustomDialog`方法用于显示弹窗,并处理从弹窗传回的回调函数结果。
3. **回调机制**:在`MyDialog`组件中,通过`showDialog`方法接收一个回调函数,并在用户点击按钮时调用该回调函数,传递相应的结果。
1 回答1k 阅读✓ 已解决
1 回答1.3k 阅读
1 回答1.1k 阅读
1 回答1.1k 阅读
1 回答1.1k 阅读
1 回答968 阅读
1 回答939 阅读
具体如下所示: