HarmonyOS 鸿蒙Next 自定义组件如何实现自己的 controller

发布于 1周前 作者 zlyuanteng 来自 鸿蒙OS

HarmonyOS 鸿蒙Next 自定义组件如何实现自己的 controller
<markdown _ngcontent-yit-c237="" class="markdownPreContainer">

如何实现自定义的controller

export class RefreshController {
  autoRefresh: (isAutoRefresh: Boolean) => void
  finishRefresh: () => void
}

 aboutToAppear() {
    if (this.refreshController) {

      this.refreshController.autoRefresh = (autoRefresh: boolean) => this.autoRefresh(autoRefresh)
      this.refreshController.finishRefresh = () => this.finishRefresh()

    }
  }
  
  
  this.refreshController.autoRefresh(true)
<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 4px; right: 8px; font-size: 14px;">复制</button>

我这么写的代码 ,调用 autoRefresh 方法 就直接崩溃了 说autoRefresh 方法没有实现.

</markdown>
5 回复
export class RefreshController {
  autoRefresh:Function =  (isAutoRefresh: Boolean) => {}
  finishRefresh:Function = () => {}
}

@Entry @Component struct Page31 { @State isRefresh: boolean = false refreshController: RefreshController = new RefreshController()

aboutToAppear() { if (this.refreshController) { this.refreshController.autoRefresh = (autoRefresh: boolean) => { this.autoRefresh(autoRefresh) } this.refreshController.finishRefresh = () => { this.finishRefresh() }

}

}

finishRefresh() { this.isRefresh = false }

autoRefresh(isRefresh: boolean) { this.isRefresh = isRefresh }

build() { Column() { Button(测试,isRefresh:${<span class="hljs-keyword"><span class="hljs-keyword">this</span></span>.isRefresh}).onClick(() => { this.refreshController.autoRefresh(true) }) Button(测试,finishRefresh).onClick(() => { this.refreshController.finishRefresh() }) } .height(‘100%’) .width(‘100%’) } }<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>

找HarmonyOS工作还需要会Flutter的哦,有需要Flutter教程的可以学学大地老师的教程,很不错,B站免费学的哦:https://www.bilibili.com/video/BV1S4411E7LY/?p=17

部分写法可以优化,提升开发体验,如下所示: export class RefreshController { autoRefresh:Function = (isAutoRefresh: Boolean) => {} finishRefresh:Function = () => {} } 说明:这么写运行没问题,不过会导致this.refreshController.autoRefresh(params)中的params不提示,比较影响使用。 建议改成: export class RefreshController { autoRefresh:(isAutoRefresh: Boolean) =>void = () => {} finishRefresh:Function = () => {} }

在HarmonyOS(鸿蒙)开发中,自定义组件实现自己的controller通常涉及几个关键步骤。首先,你需要定义组件的布局和样式,这通常在XML布局文件中完成。接着,在你的自定义组件类中,继承相应的组件基类(如Component),并实现组件的构造方法、绘制逻辑等。对于controller的实现,你可能需要根据组件的功能需求,在组件类中封装相应的业务逻辑处理代码,如事件监听、数据绑定等。确保你的组件能够正确地响应外部事件和数据变化。

如果问题依旧没法解决请加我微信,我的微信是itying888。

回到顶部