使用CustomDialogController实现。需要注意如下两点:必须在自定义弹窗1中实例化一个控制器,里面的builder传自定义弹窗2中的内容自定义弹窗1自身的控制器定义放在最后。示例代码@Entry @Component struct DialogTest { @State dialogTitle: string = ''; @State dialogData: string = ''; dialogController2: CustomDialogController = new CustomDialogController({ builder: MyDialog2({ title: '弹窗2', data: this.dialogData, confirm: this.confirm.bind(this), // 绑定自定义的回调函数,这里要修改this的指向 }), customStyle: false }) dialogController1: CustomDialogController = new CustomDialogController({ builder: MyDialog1({ controller2: this.dialogController2, title: '弹窗1', data: this.dialogData, confirm: this.confirm.bind(this) // 绑定自定义的回调函数,这里要修改this的指向 }), customStyle: false }) confirm(data: string) { this.dialogData = data; console.info(`recv dialog data: ${data}`); // 获取弹窗输入的信息 } build() { Row() { Column({ space: 10 }) { Button('点击打开弹窗1') .onClick(() => { this.dialogController1.open(); }) Text(`接受弹窗的数据:`) .fontSize(20) TextInput({ placeholder: "输入内容", text: this.dialogData }) .width("50%") .onChange((data) => { this.dialogData = data; // 获取输入框数据 }) }.width("100%") }.height("100%") } } // 弹窗组件 @CustomDialog struct MyDialog1 { controller2: CustomDialogController controller1: CustomDialogController title: string = ''; confirm: (data: string) => void = () => { }; data: string = ''; build() { Row() { Column({ space: 10 }) { Text(this.title) .fontSize(30) .fontColor(Color.Blue) Button('点击打开弹窗2') .onClick(() => { this.controller2.open(); }).backgroundColor(0xffffff).fontColor(Color.Red) Flex({ justifyContent: FlexAlign.SpaceAround }) { Button('cancel') .onClick(() => { this.controller1.close(); }).backgroundColor(0xffffff).fontColor(Color.Black) }.width("100%") }.width("50%") }.height("50%") } } // 弹窗组件 @CustomDialog struct MyDialog2 { controller: CustomDialogController; title: string = ''; confirm: (data: string) => void = () => { }; data: string = ''; build() { Row() { Column({ space: 10 }) { Text(this.title) .fontSize(30) .fontColor(Color.Blue) TextInput({ placeholder: "输入内容", text: this.data }) .onChange((data) => { this.data = data; // 获取输入框数据 }) Flex({ justifyContent: FlexAlign.SpaceAround }) { Button('cancel') .onClick(() => { this.controller.close(); }).backgroundColor(0xffffff).fontColor(Color.Black) Button('confirm') .onClick(() => { this.confirm(this.data); // 将输入框数据通过回调函数传给主页面 this.controller.close(); }).backgroundColor(0xffffff).fontColor(Color.Red) }.width("100%") }.margin({ bottom: 10 }) }.height("50%") } }
使用CustomDialogController实现。需要注意如下两点:
示例代码