我试图在NativeScript中获取和使用列表的索引,在本例中使用Repeater。
这是我的代码:
<ScrollView>
<Repeater items="{{ sviArtikli }}" itemTemplateSelector="$index">
<Repeater.itemsLayout>
<WrapLayout orientation="horizontal"/>
</Repeater.itemsLayout>
<Repeater.itemTemplate>
<Card:CardView margin="10" width="45%" height="250" item="{{ id }}" myIndex="{{ $index }}" tap="detaljiArtikla">
<grid-layout rows="250, *" columns="*, 50">
<Image loaded="slikaUcitana" class="lista-katalozi-slika" id="slicice" opacity="1" stretch="aspectFill" colSpan="3" row="0" src="{{ 'https://url_location/' + slika_image }}" />
</grid-layout>
</Card:CardView>
</Repeater.itemTemplate>
</Repeater>
</ScrollView>在复发器中,不使用myIndex="{{ $index }}"的部件不能作为索引计算。有方法可以为中继器中的每个项目获取索引吗?- ListView工作,但在这种情况下我不能使用listview。
发布于 2019-07-19 04:19:49
我已经为您创建了一个这里。您可以在数据提供程序中传递唯一的ID,并可以在项中访问。
有一个开放的Feature-request来支持中继器的索引,你也可以在那里投票。
发布于 2019-07-19 06:22:11
Repeater中还不支持访问项索引,但是如果它对您至关重要,则可以扩展Repeater类以支持索引。
indexed-repeater.ts (针对tns核心模块v6.0.1进行测试)
import { Repeater } from "tns-core-modules/ui/repeater";
import { CSSType } from "tns-core-modules/ui/layouts/layout-base";
import { parse } from "tns-core-modules/ui/builder";
export module knownTemplates {
export const itemTemplate = "itemTemplate";
}
@CSSType("Repeater")
export class IndexedRepeater extends Repeater {
public refresh() {
if (this.itemsLayout) {
this.itemsLayout.removeChildren();
}
if (!this.items) {
return;
}
const length = this.items.length;
for (let i = 0; i < length; i++) {
const viewToAdd = this.itemTemplate ? parse(this.itemTemplate, this) : (<any>this)._getDefaultItemContent(i);
const dataItem = (<any>this)._getDataItem(i);
viewToAdd.bindingContext = {
item: dataItem,
index: i
};
this.itemsLayout.addChild(viewToAdd);
}
(<any>this)._isDirty = false;
}
}示例使用
<ScrollView xmlns:comps="components/indexed-repeater">
<comps:IndexedRepeater items="{{ items }}">
<comps:IndexedRepeater.itemTemplate>
<Label text="{{ index + ' ' + item.name }}" class="m-10 h3" />
</comps:IndexedRepeater.itemTemplate>
</comps:IndexedRepeater>
</ScrollView>发布于 2019-07-19 23:18:48
嗨,伙计们,谢谢,这很有帮助。我所做的是,在不改变任何代码库的情况下,将本地生成的ID推入JSON元素,并将它们用于索引。现在json已经{ "my_index":"0“.}在fetch结束时,我在for循环中更改。我使用这些索引只是为了滚动列表中某些元素的视图。
http.getJSON("https://....")
.then(function (response){
for(var i = 0; i < response.length; i++) {
response[i].my_index = i; // change response on the fly.
// do something with response....
}
}, function(error) {
console.error(JSON.stringify(error));
})我想这对某人也有帮助。
https://stackoverflow.com/questions/57103636
复制相似问题