HarmonyNote.TOP鸿蒙开发笔记

自定义弹层CustomDialog实践过程

通过@CustomDialog修饰符定义了一个弹层结构体,要想在点击事件里触发显示这个弹层,需要通过一个CustomDialogController类型的句柄来调用open方法来实现,想要的关闭这个弹层调用句柄的close方法。然而当我在点击事件里调用句柄的open方法打开弹层时,未达预期并且报了一个错误如下:

C03f00/ArkCompiler                                    E     [ArkRuntime Log] TypeError: class constructor cannot call

于是检查代码,发现是在触发@CustomDialog组件的父组件(@Component修饰)里,定义CustomDialogController类型的外部句柄属性时,给构造函数builder参数只传递了结构体名字,由于缺少了括号()导致报上述错误,正确的定义外部CustomDialogController类型句柄的代码示例如下:

@Component
struct xxx{
  customDialogController: CustomDialogController = new CustomDialogController({
    builder: someCustomeDialogStruct()
  })
  build() { 
    // some UI
  }
}

实践过程中,在调用open方法显示弹层时,报了一个错误如下:

A default value is required for a component attribute that can be initialized locally. (mandatory-default-value-for-local-initialization)
Rule Details
If a component attribute supports local initialization, a valid, runtime-independent default value should be set for it.

由于网上参考资料很少,于是在DevEco Studio里双击错误日志行,显示错误出自“customDialogController: CustomDialogController”这行代码,于是通过编辑器类型追踪功能进到CustomDialogController源码里查看,然后又通过API Reference定位到CustomDialogController文档,找到官方示例发现需要在CustomDialogController类型的内部句柄属性名后加上?运算符,表示该句柄为可选项,修改后代码如下:

@CustomDialog
struct SomeCustomDialog{
  customDialogControllerHandler?: CustomDialogController
  build() {
    Column(){
      //some UI
    }.width('100%')
    .height('100%')
  }
}

CustomDialogController句柄的customStyle参数控制着自定义弹层的样式,如果customStyle=false则会显示默认样式,居中四周留有空白无法全屏显示;如果想要全屏显示则需要将customStyle设置为true,这样就会按照@CustomDialog修饰的结构体自定义样式来显示弹层。代码示例如下:

@Component
struct xxx{
  customDialogController: CustomDialogController = new CustomDialogController({
    builder: someCustomeDialogStruct(),
    // 应用自定义样式
    customStyle: true
  })
  build() { 
    // some UI
  }
}