在HarmonyOS NEXT开发中有回调函数的全局自定义弹窗代码例子?

在HarmonyOS NEXT开发中有回调函数的全局自定义弹窗代码例子?

阅读 1.1k
avatarAI BotBETA

在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 个回答

具体如下所示:

// CustomDialog_Globally.ets 
import { BusinessError } from '@ohos.base'; 
// CustomDialog_Globally_other01.ets 
import { ComponentContent } from '@kit.ArkUI'; 
import { buildText, Params } from './CustomDialog_Globally'; 
 
export class Params { 
  text: string = "" 
  callback: (volumeType: string, value: number) => void = () => { 
  }; 
 
  constructor(text: string, callback: (volumeType: string, value: number) => void) { 
    this.text = text; 
    this.callback = callback; 
  } 
} 
 
@Builder 
export function buildText(params: Params) { 
 
  // 弹窗内容 
  Column() { 
    Text(params.text) 
      .fontSize(50) 
      .fontWeight(FontWeight.Bold) 
      .margin({ bottom: 36 }) 
    Button("登录") 
      .onClick(() => { 
        params.text = 'button 点击登录了' 
        // 登录结果回调 
        params.callback('1', 2) 
      }) 
  }.backgroundColor(Color.Yellow) 
} 
 
 
@Entry 
@Component 
struct CustomDialog_Globally { 
  @State message: string = "hello" 
 
  build() { 
    Row() { 
      Column() { 
        Button("click me") 
          .onClick(() => { 
            let uiContext = this.getUIContext(); 
            let promptAction = uiContext.getPromptAction(); 
            // let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message)); 
            try { 
              // promptAction.openCustomDialog(contentNode); 
            } catch (error) { 
              // let message = (error as BusinessError).message; 
              let code = (error as BusinessError).code; 
              // console.error(`OpenCustomDialog args error code is ${code}, message is ${message}`); 
            } 
            ; 
          }) 
      } 
      .width('100%') 
      .height('100%') 
    } 
    .height('100%') 
  } 
} 
 
 
@Entry 
@Component 
struct CustomDialog_Globally_other01 { 
  @State message: string = 'Hello World'; 
 
  build() { 
    Column() { 
      Text(this.message) 
        .id('HelloWorld') 
        .fontSize(50) 
        .fontWeight(FontWeight.Bold) 
        .onClick(() => { 
          let uiContext = this.getUIContext(); 
          let promptAction = uiContext.getPromptAction(); 
          let callback = (volumeType: string, value: number) => { 
            //处理返回值的逻辑 
            console.log(`OpenCustomDialog args error code is ${volumeType}, message is ${value}`); 
            this.message = volumeType; 
          } 
          let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message, callback)); 
          try { 
            promptAction.openCustomDialog(contentNode); 
          } catch (error) { 
            let message = (error as BusinessError).message; 
            let code = (error as BusinessError).code; 
            console.error(`OpenCustomDialog args error code is ${code}, message is ${message}`); 
          } 
          ; 
        }) 
    } 
    .height('100%') 
    .width('100%') 
  } 
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进