在离子组件中,我使用了令人惊叹的<ion-virtual-scroll>
标签。为了拆分列表中的项目,标题功能令人惊讶。现在,分离此代码,我将其部分提取到私有函数sameGroup
中。虽然当我想从TypeError: this is undefined
函数调用它时返回myHeaderFn
。为什么?
(是的,我知道,我可以轻松地将该功能代码插入myHeaderFn
。但这不是问题。)
@Component({
selector: 'app-stash',
templateUrl: './stash.page.html',
styleUrls: ['./stash.page.scss'],
})
export class StashPage implements OnInit {
public translations: Translation[];
constructor(private translationService: TranslationService) { }
ngOnInit() {
this.translations = this.translationService.getAllTranslationsSorted('de', 'ar');
}
myHeaderFn(record, recordIndex, records) {
if (**this.sameGroup(recordIndex, records)**) {
return null;
} else {
return record['term'].substring(0, 1);
}
}
private sameGroup(i, records) {
if (i === 0) {
return false;
} else {
const prevRecInitLet = records[i - 1]['term'].substring(0, 1);
const currRecInitLet = records[i]['term'].substring(0, 1);
return prevRecInitLet === currRecInitLet ? true : false;
}
}
}
myHeaderFn
由离子成分ion-virtual-scroll
调用。
<ion-virtual-scroll [items]="translations" [headerFn]="myHeaderFn">
<ion-item-divider *virtualHeader="let header">
{{ header }}
</ion-item-divider>
<!-- need to wrap this into the div, so that *virtualItem is not part of the component -->
<div *virtualItem="let trans">
<!-- translation (not translations) referes to the model of the component -->
<app-transitem [translation]=trans></app-transitem>
</div>
</ion-virtual-scroll>
答案 0 :(得分:1)
您需要使用箭头功能。
myHeaderFn = (record, recordIndex, records) => {
if (this.sameGroup(recordIndex, records)) {
return null;
} else {
return record['term'].substring(0, 1);
}
}
箭头函数没有自己的此值。箭头函数中的this的值始终从封闭范围继承。
https://hacks.mozilla.org/2015/06/es6-in-depth-arrow-functions/