在官方文檔下恨旱,有以下描述:
CustomDialogController僅在作為@CustomDialog和@Component struct的成員變量座慰,且在@Component struct內(nèi)部定義時(shí)賦值才有效
對(duì)于面向?qū)ο蟮拈_(kāi)發(fā)思想來(lái)說(shuō)往堡,我們只想用一套代碼械荷,而不用到處進(jìn)行初始化定義,因此虑灰,經(jīng)過(guò)長(zhǎng)達(dá)兩天半的搜索及琢磨吨瞎,有以下的方式,應(yīng)符合大部分的場(chǎng)景需求瘩缆。
不多說(shuō)关拒,上封裝代碼:
// 封裝常用的入?yún)?export interface AppDialogOptions {
width?: Dimension
height?: Dimension
alignment?: DialogAlignment
isTip: boolean
isCheck?: boolean
message?: string | Resource
password?: (password?: string) => void // 獲取自定義view返回的數(shù)據(jù)
}
// 封裝的CustomDialogController
export function CreateDialog(options: AppDialogOptions): CustomDialogController {
let controller = new CustomDialogController({
width: options.width,
height: options.height,
alignment: options.alignment,
builder: QuickDialogView({
isTip: options.isTip,
tipMsg: options.message,
isCheck: options.isCheck,
cancel: (code?: string) => {
controller.close() // 需要在這里進(jìn)行close,在自定義view里使用controller.close會(huì)崩潰
if (options.password) {
options.password(code)
}
}
})
})
return controller
}
以下是庸娱,使用的示例代碼:
// 這里一定要使用bind進(jìn)行綁定
private quickDialog: CustomDialogController = CreateDialog.bind(this)({
width: '97%',
height: '30%',
alignment: DialogAlignment.Center,
password: (code?: string) => {
console.error(`whz--->${code}`)
}
})
// 備注:若是參數(shù)什么都是確定着绊,只需創(chuàng)建對(duì)象記得bind(this)后的()一定要帶,否則會(huì)崩潰
private quickDialog: CustomDialogController = CreateDialog.bind(this)()
至此熟尉,封裝使用归露,皆完成!=锒剧包!