HarmonyOS 父子组件互相调用问题?

在父组件里面创建一个类实例传递给子组件,这个类实例有一个方法可以push数据到一个数组,然后类里面有一个定时器会去这个数组里面取数据出来消费。子组件push的数据在定时器回调里面看不见,只能看见父组件push的数据。

代码如下:

export class Test {
  private queue: number[] = []
  private timer: number | null = null
  constructor() {
    this.timer = setInterval(() => {
      if (this.queue.length) {
        console.log('pop:', this.queue.shift())
      }
    }, 1000)
  }

  push(a: number) {
    this.queue.push(a)
    console.log('push:', a)
  }
}

@Component
struct Children {
  @Prop @Require test: Test
  build() {
    Column() {
      Text('我是子组件')
    }
  }

  aboutToAppear(): void {
    setInterval(() => {
      this.test.push(1)
    }, 1000)
  }
}

@Entry
@Component
struct Index {
  private test: Test = new Test()
  build() {
    Column() {
      Text('我是父组件')
      Children({
        test: this.test
      })
    }
  }

  aboutToAppear(): void {
    setInterval(() => {
      this.test.push(2)
    }, 1000)
  }
}

可以看见push日志有1和2,pop只有2。

阅读 454
1 个回答

@Prop装饰器指的是父子单向同步,可以使用@Link(父子双向同步),参考demo:

import {Test,Children} from './Page'
@Entry
@Component
struct Page {
  // private test: Test = new Test()
  @State test: Test = new Test()
  build() {
    Column() {
      Text('我是父组件')
      Children({
        test: this.test
      })
    }
  }

  aboutToAppear(): void {
    setInterval(() => {
      this.test.push(2)
    }, 1000)
  }
}

export class Test {
  private queue: number[] = []
  private timer: number | null = null
  constructor() {
    this.timer = setInterval(() => {
      if (this.queue.length) {
        console.log('pop:', this.queue.shift())
      }
    }, 1000)
  }
  push(a: number) {
    this.queue.push(a)
    console.log('push:', a)
  }
}
@Component
export struct Children {
  // @Prop @Require test: Test
  @Link test: Test
  build() {
    Column() {
      Text('我是子组件')
    }
  }

  aboutToAppear(): void {
    setInterval(() => {
      this.test.push(1)
    }, 1000)
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进