我有以下 View XML:
<ListView items="{{ lists }}" itemTap="itemTapped">
<ListView.itemTemplate>
<StackLayout class="list-group-item" orientation="horizontal">
<Label text="{{ name }}" class="item-name" horizontalAlignment="center" />
</StackLayout>
</ListView.itemTemplate>
</ListView>
在 itemTapped
中,我想更改 StackLayout 容器的背景颜色。
exports.itemTapped = function (args) {
console.log(args.object.backgroundColor)
args.object.backgroundColor = 'red'
console.log(args.object.backgroundColor)
}
当我运行应用程序并单击列表项时,我会在控制台中看到以下内容:
CONSOLE LOG file:///app/pick/pick-page.js:111:14: undefined
CONSOLE LOG file:///app/pick/pick-page.js:113:14: #FF0000
CONSOLE LOG file:///app/pick/pick-page.js:111:14: undefined
CONSOLE LOG file:///app/pick/pick-page.js:113:14: #FF0000
我还尝试了在CSS中设置background-color: red;
的args.object.className = 'selected-item'
,但这也不起作用。
如何动态更改该颜色?或者,是否有更好的方法来指示 ListView 项目被点击?
最佳答案
您不应该直接从 ListView 修改 ListItem,因为当您向上/向下滚动时,元素可能会被重用。您的数据项上应该有一个属性,并根据该属性切换该属性,您可以在 ListItem 上绑定(bind)背景颜色。
<ListView items="{{ countries }}" itemTap="{{ onItemTap }}">
<ListView.itemTemplate>
<FlexboxLayout flexDirection="row"
backgroundColor="{{ selected, selected ? 'red' : 'white' }}">
<Image src="{{ imageSrc }}" class="thumb img-circle" />
<Label text="{{ name }}" class="t-12"
verticalAlignment="center" style="width: 60%" />
</FlexboxLayout>
</ListView.itemTemplate>
</ListView>
关于javascript - 如何在 NativeScript 中更改 StackLayout 容器的背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59062391/