arkui-x 页面封装为自定义组件,巧用controller
鸿蒙开发中,有时会需要将某些页面封装为自定义组件,方便复用。
页面的入口为:
@Entry
@Component
struct XXX {
。。。。。。
自定义组件的入口为:
@Component
export struct XXXX {
。。。。。。
但是页面与自定义组件在生命周期上是有一些不同的。
重点在于页面支持onPageShow():在页面每次显示时调用。通常页面数据需要在这个接口里刷新,以保证数据最新。
而自定义组件不支持onPageShow()接口,只有aboutToAppear()接口,用于组件初始化数据。
所以把页面封装为自定义组件,遇到的最大问题就是数据刷新问题。
解决思路:自定义组件自己无法刷新,就让调用方来刷新数据。换一个说法就是,要支持父组件调用子组件接口。
arkui-x框架给了一个方案,就是定义controller接口。示例如下:
封装的自定义组件NewSon,定义class NewSonController的接口定义,NewSon组件初始化时给refreshData函数接口赋值。这个写法有点像AIDL。
export class NewSonController {
refreshData = () => {}
}
@Component
export struct NewSon {
controller: NewSonController = new NewSonController();
refreshData = () => {
this.uptData()
}
aboutToAppear() {
if (this.controller) { //给controller对应的方法赋值
this.controller.refreshData = this.refreshData;
}
}
。。。。。。
build() {
。。。。。。
父组件增加下面定义,与调用点:
@Entry
@Component
struct FartherPage {
。。。。。。
childRef = new NewSonController(); // Controller接口,获取子组件刷新数据的接口的引用
onPageShow() {
。。。。。。
this.childRef.refreshData() // 每次页面显示时,刷新子组件数据
}
。。。。。。
build() {
。。。。。。
NewSon({ controller: this.childRef })
。。。。。。
}
这里父组件是一个页面,调用NewSon组件时,传入了this.childRef作为controller。然后可在onPageShow里调用this.childRef.refreshData,间接达到刷新子组件数据的效果。