文章目录
- 一、目标
- 二、开撸
- 2.1 自定义弹窗
- 2.2 主页面事件处理
- 2.3 主页面完整代码
- 三、小结
一、目标
二、开撸
2.1 自定义弹窗
@CustomDialog
export struct SinglePreviewDialog {// 弹窗控制器 mustcontroller: CustomDialogController// 展示图片URLimgUrl: ResourceStr = ''build() {Column() {Image(this.imgUrl).width('100%')}.width('100%').height('100%').justifyContent(FlexAlign.Center).backgroundColor(Color.Black).onClick(() => {// 关闭弹窗this.controller.close()})}
}
2.2 主页面事件处理
声明变量,记录当前选择图片地址:
selectImgUrl: ResourceStr = ''
声明自定义Dialog
对象:
singlePreviewDialog: CustomDialogController = new CustomDialogController({builder: SinglePreviewDialog({imgUrl: this.selectImgUrl}),customStyle: true //使用自定义Dialog的样式
})
图片注册点击事件:
Image(item.imgUrl).aspectRatio(1).onClick(() => {this.selectImgUrl = item.imgUrlthis.singlePreviewDialog.open()})
2.3 主页面完整代码
import { PhotoAlbumView } from './components/PhotoAlbumView';
import { SelectImageItem } from './models';
import { promptAction } from '@kit.ArkUI';
import { SinglePreviewDialog } from './dialog/SinglePreviewDialog';@Entry
@Component
struct PhotoAlbumDemoPage {@State message: string = 'Hello World';@State showPhotoAlbum: boolean = false@State selectImgList: SelectImageItem[] = []// 当前选中图片selectImgUrl: ResourceStr = ''// 单图预览dialogsinglePreviewDialog: CustomDialogController = new CustomDialogController({builder: SinglePreviewDialog({imgUrl: this.selectImgUrl}),customStyle: true //使用自定义Dialog的样式})build() {Column() {Button('打开相册').onClick(() => {this.showPhotoAlbum = true})Text('已选择图片:').width('100%').textAlign(TextAlign.Start)if (this.selectImgList && this.selectImgList.length) {Grid() {ForEach(this.selectImgList, (item: SelectImageItem) => {GridItem() {Stack() {Image(item.imgUrl).aspectRatio(1).onClick(() => {this.selectImgUrl = item.imgUrlthis.singlePreviewDialog.open()})}}}, (item: SelectImageItem) => JSON.stringify(item))}.columnsTemplate('1fr 1fr 1fr').columnsGap(5).rowsGap(5).padding(10).layoutWeight(1)}if (this.showPhotoAlbum) {PhotoAlbumView({maxNumber: 5,cancel: () => {this.showPhotoAlbum = false},confirm: (selectImgList: SelectImageItem[]) => {this.showPhotoAlbum = falsethis.selectImgList = [...this.selectImgList, ...selectImgList]}})}}.width('100%').height('100%')}
}
三、小结
open
创建弹层组件-显示-会有动画的弹出close
销毁组件-推出-会有动画的退出open/close
会创建和销毁组件,不存在缓存现象,里面的参数实际上没有任何必要使用@State
修饰符customStyle
是否允许自定义的样式设置,因为默认的弹层是有一些定制的样式的