在app中实现一个Toast组件功能,使用自定义弹窗组件进行二次封装,关键代码如下:
struct CustomerDialogToast{
controller?: CustomDialogController;
@Prop type:string = "info"
@Prop info:string = ""
build() {
Column(){
if(this.type=="info"){
Text(this.info)
.fontSize(CommonConstants.fontSize)
.fontColor(CommonConstants.fontColorInfo).maxLines(1)
}
if (this.type=="loading"){
}
}
.width(CommonConstants.toastWidth)
.borderRadius(CommonConstants.borderRadius)
.borderColor(CommonConstants.borderColor)
.borderWidth(CommonConstants.borderWidth)
.backgroundColor(CommonConstants.backgroundColor)
.padding({
top:CommonConstants.paddingTop,bottom:CommonConstants.paddingTop,
left:CommonConstants.paddingLeft,right:CommonConstants.paddingLeft
})
}
}
@Component
export struct CustomDialogUser{
@Prop type:string = "info"
@Prop info:string = ""
@Link @Watch('onShowUpdate') showToast:boolean;
dialogController:CustomDialogController |null = new CustomDialogController({
builder:CustomerDialogToast({type:this.type,info:this.info}),
openAnimation: {
duration: CommonConstants.DURATION,
curve: Curve.Friction,
delay: CommonConstants.DELAY,
playMode: PlayMode.Alternate
},
closeAnimation: {
duration: CommonConstants.DURATION,
curve: Curve.Friction,
delay: CommonConstants.DELAY,
playMode: PlayMode.Alternate
},
alignment: DialogAlignment.Bottom,
offset: { dx: 0, dy: CommonConstants.offsetY},
customStyle: true,
cornerRadius:CommonConstants.cornerRadius,
isModal: false
})
onShowUpdate(value:boolean){
console.log("点击",this.showToast)
this.info = this.info
if(this.showToast){
this.dialogController?.open()
setTimeout(()=>{
this.dialogController?.close()
this.showToast = false
},3000)
}else{
this.dialogController?.close()
this.showToast = false
}
}
aboutToDisappear(){
this.dialogController = null
}
build() {
}
}
然后在其他组件引入CustomDialogUser。
build() {
Column(){
CustomDialogUser({ info: this.showInfo, type: "info",showToast:this.showToast })
}
在处理逻辑上
if(!this.isValidPhone){
this.showInfo = "请输入正确手机号 !"
this.showToast = true
return
}
if(!this.isChecked){
this.showInfo = "请阅读并同意协议 !"
this.showToast = true
return
}
if(!this.isCoded){
this.showInfo = "请输入验证码 !"
this.showToast = true
return
}
第一次弹窗内容为空 ,直到第二次点击才显示 “请输入正确手机号”的提示,如何解决第一次文字提醒为空?
在builder构造器中监听数据变化要使用使用@Link。