如果列表中项目的位置会动态改变或者有新的项目添加到列表中,并且希望列表中的项目保持自己的特征和状态(如 <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; }