如何在ng2-smart-table的filterFunction中调用组件方法?
解决ng2-smart-table filterFunction中调用组件方法的this指向问题
我来帮你搞定这个问题!你遇到的是JavaScript/TypeScript里常见的this上下文绑定问题——ng2-smart-table的filterFunction作为配置对象中的函数,执行时的this并不会指向你的组件实例,而是脱离了上下文变成null,所以直接调用this.doFilter才会报错。下面给你几个实用的解决方案:
方案1:使用箭头函数(最推荐)
箭头函数不会创建自己的this,它会捕获外层(也就是你的组件类)的this上下文,所以能直接访问组件的doFilter方法。修改代码如下:
export class SmartTableComponent { settings = { // ...其他配置 columns: { // ...其他列 firstName: { title: 'First Name', type: 'string', filterFunction: (cell?: any, search?: string): boolean => { return this.doFilter(cell, search); } }, // ...其他列 }, // ...其他配置 }; doFilter(cell?: any, search?: string): boolean{ return true; } }
这个方案代码最简洁,可读性也最高,是处理这类this问题的首选方式。
方案2:在构造函数中绑定this
你可以在组件的构造函数里,把doFilter方法的this绑定到组件实例上,然后在filterFunction里调用绑定后的函数:
export class SmartTableComponent { private boundDoFilter: (cell?: any, search?: string) => boolean; constructor() { // 将doFilter的this绑定到当前组件实例 this.boundDoFilter = this.doFilter.bind(this); } settings = { // ...其他配置 columns: { // ...其他列 firstName: { title: 'First Name', type: 'string', filterFunction(cell?: any, search?: string): boolean { return this.boundDoFilter(cell, search); } }, // ...其他列 }, // ...其他配置 }; doFilter(cell?: any, search?: string): boolean{ return true; } }
bind方法会创建一个新函数,这个函数的this会被固定为你传入的组件实例,所以不管filterFunction在什么上下文执行,都能正确调用组件的doFilter方法。
方案3:提前缓存组件实例引用
你可以在组件类里定义一个变量(比如self)来保存组件实例的引用,然后在filterFunction里用这个变量代替this:
export class SmartTableComponent { private self = this; // 缓存组件实例 settings = { // ...其他配置 columns: { // ...其他列 firstName: { title: 'First Name', type: 'string', filterFunction(cell?: any, search?: string): boolean { return this.self.doFilter(cell, search); } }, // ...其他列 }, // ...其他配置 }; doFilter(cell?: any, search?: string): boolean{ return true; } }
这个方案也能解决问题,但代码相对冗余,不如前两个方案优雅,所以只作为备选。
总结一下,方案1的箭头函数是最优解,它能最简洁地解决this指向问题,让你顺利在filterFunction中调用组件的方法。
内容的提问来源于stack exchange,提问作者pellyadolfo
相关产品推荐
相关产品推荐

