📌 场景背景

在实际开发中,Modal 弹窗常用于提示、确认、表单等交互场景。与页面强耦合会导致复用性低。我们将构建一个支持全局调用、灵活配置的共享弹窗组件。


🧩 Step 1:定义弹窗组件 GlobalModal.ets

// components/GlobalModal.ets
@Component
export struct GlobalModal {
  @State isVisible: boolean = false;
  @State title: string = '';
  @State content: string = '';
  private onConfirm?: () => void;

  show(options: { title: string; content: string; onConfirm?: () => void }) {
    this.title = options.title;
    this.content = options.content;
    this.onConfirm = options.onConfirm;
    this.isVisible = true;
  }

  private handleConfirm() {
    this.isVisible = false;
    this.onConfirm?.();
  }

  build() {
    if (!this.isVisible) return;

    Column() {
      Text(this.title).fontSize(20).fontWeight(FontWeight.Bold).padding(10)
      Text(this.content).fontSize(16).padding(10)

      Row() {
        Button("取消").onClick(() => this.isVisible = false)
        Button("确定").onClick(() => this.handleConfirm())
      }.margin({ top: 10 })
    }
    .backgroundColor('#fff')
    .borderRadius(12)
    .padding(20)
    .align(Alignment.Center)
  }
}

🧩 Step 2:挂载并暴露控制器

// common/modalManager.ts
import GlobalModal from '../components/GlobalModal';

let modalRef: GlobalModal | null = null;

export function registerModal(ref: GlobalModal) {
  modalRef = ref;
}

export function showModal(options: { title: string; content: string; onConfirm?: () => void }) {
  modalRef?.show(options);
}

🧩 Step 3:在主页面挂载 Modal 组件

// pages/index/index.ets
import { registerModal, showModal } from '../../common/modalManager';
import GlobalModal from '../../components/GlobalModal';

@Entry
@Component
struct MainPage {
  @State modalInstance: GlobalModal = new GlobalModal();

  aboutToAppear() {
    registerModal(this.modalInstance);
  }

  build() {
    Column() {
      Button("点击弹窗").onClick(() => {
        showModal({
          title: '提示',
          content: '是否确认执行操作?',
          onConfirm: () => {
            console.info('用户确认操作');
          }
        });
      })

      this.modalInstance.build()
    }
  }
}

✅ 效果预览

点击按钮即可唤起统一风格的弹窗组件,用户点击“确认”执行回调,点击“取消”关闭。


⚠️ 易错点提示

问题 说明
modalRef 未注册 showModal 调用无效,需在页面初始化注册一次
弹窗未插入 UI 树 需要手动将 modalInstance.build() 加入页面中
状态未用 @State 控制 弹窗无法响应式更新

🧠 拓展建议

  • 增加动画过渡效果(用 animateTo);

  • 支持 Alert、Confirm、Prompt 类型切换;

  • 可进一步封装为 DialogManager 支持多弹窗实例。


Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐