随笔 - 91,  文章 - 0,  评论 - 4,  阅读 - 13万

如果列表中项目的位置会动态改变或者有新的项目添加到列表中,并且希望列表中的项目保持自己的特征和状态(如 <input/> 中的输入内容,<switch/> 的选中状态),需要使用 wx:key 来指定列表中项目的唯一的标识符。

wx:key 的值以两种形式提供

  1. 字符串,代表在 for 循环的 array 中 item 的某个 property,该 property 的值需要是列表中唯一的字符串或数字,且不能动态改变。
  2. 保留关键字 *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;
}

 

posted on   xiao孛  阅读(5968)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示