且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

打字稿错误:@viewChild 未定义

更新时间:2022-06-18 07:13:15

就像你在 中看到的Angular 文档,

ViewChild 在视图初始化后设置

ViewChild is set after the view has been initialized

ViewChild 在视图被检查后更新

ViewChild is updated after the view has been checked

export class AfterViewComponent implements  AfterViewChecked, AfterViewInit {

  ngAfterViewInit() {
    // viewChild is set after the view has been initialized <- Here!
  }

  ngAfterViewChecked() {
    // viewChild is updated after the view has been checked <- Here!
  }

  // ...

}

因此,您的代码的问题是在执行构造函数时视图尚未初始化.您需要将与选项卡交互的所有代码放在 ngAfterViewInit 生命周期挂钩中:

So the issue on your code is that the view has not been initialized when the constructor is executed. You'd need to put all the code that interacts with the tabs in the ngAfterViewInit lifecycle hook:

  ngAfterViewInit() {
    // Now you can use the tabs reference
    console.log("a = ", this.tabRef);
  }

如果您只想使用 Ionic 自定义生命周期事件,则需要使用 ionViewDidEnter 挂钩:

If you just want to use Ionic custom lifecycle events, you'd need to use the ionViewDidEnter hook:

export class TabsPage {

@ViewChild('myTabs') tabRef: Tabs;

ionViewDidEnter() {
    // Now you can use the tabs reference
    console.log("a = ", this.tabRef);
 }

}