如果列表中项目的位置会动态改变或者有新的项目添加到列表中,并且希望列表中的项目保持自己的特征和状态(如 <input/>
中的输入内容,<switch/>
的选中状态),需要使用 wx:key
来指定列表中项目的唯一的标识符。
wx:key
的值以两种形式提供
- 字符串,代表在 for 循环的 array 中 item 的某个 property,该 property 的值需要是列表中唯一的字符串或数字,且不能动态改变。
- 保留关键字
*this
代表在 for 循环中的 item 本身,这种表示需要 item 本身是一个唯一的字符串或者数字,如:numberArray: [1, 2, 3, 4]
wxml文件:
<view class="userList" wx:for="{{items}}" wx:key="{{item.userId}} wx:for-index="idx""> <view class="{{userCellId==idx?'userCellActive':'userCell'}}" data-idx="{{idx}}" bindtap="userListAction">{{item.name}}</view> </view>
1、page.data里设一个变量,比如userCellId(JS文件在下面👇)
2、列表项里增加一个属性data-id="{{idx}}"
3、在列表项的userListAction事件里this.setData({userCellId: e.target.dataset.idx})
4、列表项的class里根据userCellId设置不同样式,如class="{{userCellId==idx?'userCellActive':'userCell'}}"
5、wxss里定义.userCellActive和.userCell样式的背景颜色。
JS文件
Page({
data:{
items:[
{
userId: 1,
name: "user1",
},
{
userId: 2,
name: "user2",
},
{
userId: 3,
name: "user3",
}
],
userCellId: 0
},
userListAction:function(e){
console.log(`点击了${e.target.dataset.idx}`)
this.setData({
userCellId: e.target.dataset.idx
})
}
})
wxss文件
.userCell{ background-color: red; } .userCellActive{ background-color: green; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了