作者
novlan1
2025.11.30
PixUI 中的组件命令式调用
1. 介绍
Press Pix 中有几个组件已支持动命令式调用,如 Toast 和 PmgPopupContainer(Dialog),并抽离公共部分,可复用到其他业务。
具体支持组件如下(截止到 2025.11.30)。
- Toast
- PmgToast
- PmgPopupContainer
支持命令式调用组件非常重要,除了在业务中方便使用外,还可以在网络框架中实现全局失败提示。想象下,没有命令式调用,每次请求失败怎么做呢?EventBus 抛出事件,页面自行监听,自行处理?是不是代码量、工作量太大了,容易遗漏、容易出错。
2. 使用方式
动态组件可分为下面几种类型。
2.1. Toast 类型
以 Toast 组件为例
tsx
import { showToast } from 'press-pix/toast/command';
showToast('hello novlan1');
// 第二个参数为 duration,持续时间
// 具体可参考具体组件文档
showToast('hello novlan1', 1000);(就是这么简单!)
手动关闭方式如下:
tsx
import { toast } from 'press-pix/toast/command';
// toast.show 等价于 showToast
toast.show('hello novlan1');
// 手动关闭
toast.clear();2.2. Dialog 类型
以 PmgPopupContainer 组件为例
tsx
import { dialog } from 'press-pix/pmg-popup-container/command';
dialog.show({
size: 'small',
title: '接受系统调配',
titleColor: '#fff',
cancelText: '再想想',
confirmText: '接受调配',
smallText: '队员人数少时,有可能解散您的队伍,合入他人队伍',
onClickCancel() {
// 这里手动关闭
dialog.close();
},
onClickClose() {
dialog.close();
},
onClickConfirm() {
setIsAcceptAssign(true);
dialog.close();
},
});3. 公共逻辑
除了可直接使用的组件外, Press Pix 还提供了一些命令调用的公共逻辑,可复用到其他业务中。
toast类型命令调用公共逻辑,src/components/common/command-component/toast.tsxdialog类型命令调用公共逻辑,src/components/common/command-component/toast.tsx
4. FAQ
4.1. 实现原理
PixUI 可以动态创建元素,这一点比小程序还是方便很多。
展示时,动态创建一个 div 元素,并添加到 body 中。
ts
init() {
if (!this.container) {
this.container = document.createElement('div');
// 示例类名
this.container.className = 'press-dialog-container';
document.body.appendChild(this.container);
this.root = this.container;
}
}展示时用 render 方法渲染。
tsx
import { render as renderDom } from 'preact';
show() {
this.init();
const dialogElement = (
<DialogComponent
{/* 省略其他参数 */}
{/* ... */}
{...props}
/>
);
renderDom(dialogElement, this.container);
},
}关闭时,清除元素。
ts
close() {
document.body.removeChild(this.container);
this.container = null;
},