HarmonyOS 容器组件子组件个数发生变化时,有什么监听回调方法吗

HarmonyOS
2025-01-09 15:43:03
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
FengTianYa

目前暂无办法获取子组件的个数,可在传数据的时候来判断数量,传递事件可以参考以下示例:

@Component
struct Child {
  @State private text: string = '初始值'
  private controller: ChildController = new ChildController();

  aboutToAppear() {
    // 子组件调用的方法为父组件传递过来的方法
    this.controller.testFunc('im the son')
    // 将testFunc方法用子组件方法进行覆盖
    if (this.controller) {
      this.controller.testFunc = this.testFunc
    }
  }

  // 子testFunc方法的具体实现
  testFunc = (value: string) => {
    this.text = value
    console.log('[testFunc]testFunc call from Child')
    return "[testFunc]我是儿子的方法"
  }

  build() {
    Column() {
      Text(this.text)
    }
  }
}

// 定义声明testFunc方法的controller
class ChildController {
  // 定义子testFunc方法同名的空方法
  testFunc = (value: string) => {
    console.log('[testFunc]testFunc: ' + value)
    return "[testFunc]我是公共定义的空方法"
  }
}

@Entry
@Component
struct Parent {
  private ChildRef = new ChildController()

  aboutToAppear(): void {
    this.ChildRef.testFunc = this.testFunc
  }

  // 父testFunc方法的具体实现
  testFunc = (value: string) => {
    console.log('[testFunc]我是父亲的testFunc方法 : ' + value)
    return "[testFunc]我是父亲的方法"
  }

  build() {
    Column() {
      Text('获取Child的exposedMethods!').fontSize('18vp').fontColor(Color.Gray)
      Divider()
      // 将父方法作为参数传递给子组件
      Child({ controller: this.ChildRef })
      // 父组件调用子组件的方法
      Button('Parent调用children的方法').onClick(() => {
        let text = this.ChildRef.testFunc('Parent调用children的方法')
        console.info('[testFunc]testFunc info:' + JSON.stringify(text))
      })
    }
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
分享
微博
QQ
微信
回复
2025-01-09 18:53:11


相关问题
HarmonyOS 页面高度发生变化
832浏览 • 1回复 待解决
HarmonyOS 组件是否销毁方法
1374浏览 • 1回复 待解决