Angular 2/Ionic 3中如何从回调函数调用组件内方法?
解决Angular 2/Ionic 3中回调函数调用类方法的问题
你遇到的核心问题是回调函数里的this指向不对——普通function声明的回调内部,this会指向options对象本身,而不是ChatDetailPage的类实例,所以直接调用this.funcB会找不到方法。这里有几种常用的解决办法,按推荐程度排序:
1. 使用箭头函数(最推荐)
箭头函数不会创建自己的this,它会继承外层作用域的this(也就是你的类实例),写法也最简洁:
export class ChatDetailPage { constructor(){ } funcA(){ const options = { // 换成箭头函数,this自动指向ChatDetailPage实例 onSubmit: (text) => { this.funcB(text) } }; this.nativeKeyboard.showMessenger(options); } funcB(text){ alert(text); } }
2. 提前保存类实例的this
在funcA里先把当前实例的this存到一个变量(比如self/that),然后在回调里用这个变量访问方法:
export class ChatDetailPage { constructor(){ } funcA(){ // 保存类实例的this到self变量 const self = this; const options = { onSubmit: function (text) { self.funcB(text) } }; this.nativeKeyboard.showMessenger(options); } funcB(text){ alert(text); } }
3. 用bind()绑定this
通过bind()方法把回调函数的this强制绑定到类实例上:
export class ChatDetailPage { constructor(){ } funcA(){ const options = { onSubmit: function (text) { this.funcB(text) }.bind(this) // 绑定当前类实例的this到回调函数 }; this.nativeKeyboard.showMessenger(options); } funcB(text){ alert(text); } }
这三种方法都能解决问题,其中箭头函数是TypeScript/ES6+里最常用的方案,代码更简洁易读。
内容的提问来源于stack exchange,提问作者Krishna Karki
相关产品推荐
相关产品推荐

