鸿蒙NEXT 父组件调用子组件方法和子组件调用父组件方法

538 阅读1分钟

鸿蒙中父组件调用子组件中封装的方法,需要借助额外的一个类来实现。
在子组件中需要将对应的方法赋值给管理类进行关联。

父组件调用子组件

//定义controller对象
class ChildController {
  childText = (value: string) => {
  }
}

@Component
export struct ParentComponent {
  private ChildRef = new ChildController();

  build() {
    Column({ space: 10 }) {
        Text('父組件调用子组件方法').fontSize(18).fontColor(Color.Gray)
        Button('父调子').onClick(() => {
          this.ChildRef.childText('父组件传递给子组件的数据');
        })
        Child({ controller: this.ChildRef })
      }
    .justifyContent(FlexAlign.Center)
    .width('100%')
    .height('100%')
  }
}


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

  aboutToAppear() {
    if (this.controller) {
      //给controller对应的方法赋值
      this.controller.childText = this.childRealText;
    }
  }

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

  //子组件封装的方法,真正执行的方法
  private childRealText = (value: string) => {
    this.text = '子组件方法被执行:' + value
  }
}

子组件调用父组件


@Component
export struct ParentComponent {
  @State private text: string = '';

  build() {

    Column({ space: 10 }) {
      Text('子组件调用父组件方法').fontSize(18).fontColor(Color.Gray)
      Child({
        //不需要传值就把值去掉
        //func: () => {
        func: (text?: string) => {
          if (text) {
            this.parentTest(text)
          }
        }
      })
      Text(this.text)
    }
    .justifyContent(FlexAlign.Center)
    .width('100%')
    .height('100%')
  }

  parentTest(text: string) {
    this.text = '父组件方法被执行:' + text
  }
}


@Component
struct Child {
  @State private text: string = '';
  @State showButton: boolean = false
  func?: (text?: string) => void = () => {
  }

  build() {
    Column() {
      Button('子组件').onClick(() => {
        if (this.func) {
          this.func("子组件传递给父组件的数据")
        }
      })
    }
  }
}