目录

列表选择弹窗ActionSheet的sheets属性无法实时更新

问题现象

动态改变列表选择弹窗ActionSheet的sheets属性,弹窗内容无法实时更新。问题代码示例参考如下:

@Entry
@Component
struct showActionSheetExample {
  @State sheets: Array<SheetInfo> = [{
    title: 'apples',
    action: () => {
    }
  }];
  @State count: number = 0;

  build() {
    Column() {
      Button('showActionSheet')
        .margin(30)
        .onClick(() => {
          setInterval(() => {
            this.count++;
            this.sheets.push({
              title: 'bananas' + this.count,
              action: () => {
              }
            });
          }, 1000);

          this.getUIContext().showActionSheet({
            title: 'ActionSheet title',
            message: 'message',
            confirm: {
              value: 'Confirm button',
              action: () => {
                console.info('Get Alert Dialog handled');
              }
            },
            alignment: DialogAlignment.Center,
            sheets: this.sheets
          });
        });
    }.width('100%');
  }
}

背景知识

问题定位

在showActionSheet打开列表选择弹窗后,对sheets属性进行动态修改,弹窗UI未变化。

分析结论

ActionSheet列表选择弹窗不支持动态更新属性,需要通过自定义弹出框实现。

修改建议

下面通过openCustomDialog实现,并且以传builder的形式为例,实现动态更新自定义弹出框的内容。

import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  private customDialogComponentId: number = 0;
  @State count: number = 0;
  intervalId?: number;

  @Builder
  customDialogComponent() {
    Column() {
      Text('充电详情').fontSize(25);
      Text(`已充电时间:${this.count}秒`);
      Row({ space: 50 }) {
        Button('确认').onClick(() => {
          this.getUIContext().getPromptAction().closeCustomDialog(this.customDialogComponentId);
          clearInterval(this.intervalId);
        });
        Button('取消').onClick(() => {
          this.getUIContext().getPromptAction().closeCustomDialog(this.customDialogComponentId);
          clearInterval(this.intervalId);
        });
      };
    }.height(200).padding(5).justifyContent(FlexAlign.SpaceAround);
  }

  build() {
    Row() {
      Column({ space: 20 }) {
        Text('组件内弹窗')
          .fontSize(30)
          .onClick(() => {
            this.getUIContext()
              .getPromptAction()
              .openCustomDialog({
                builder: () => {
                  this.customDialogComponent();
                }
              })
              .then((dialogId: number) => {
                this.customDialogComponentId = dialogId;
              })
              .catch((error: BusinessError) => {
                console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`);
              });

            this.intervalId = setInterval(() => {
              this.count++;
            }, 1 * 1000);
          });
      }
      .width('100%');
    }
    .height('100%');
  }
}