国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 熱點 > 微信 > 正文

微信小程序 wx:key詳細介紹

2024-07-22 01:16:47
字體:
來源:轉載
供稿:網友

微信小程序 wx:key 在自己學習的時候不是多明白到底是怎么回事,經過上網查閱資料,整理下:

  個人感覺官方給出的例 子不是很明確,官方解釋如下:

wx:key

如果列表中項目的位置會動態改變或者有新的項目添加到列表中,并且希望列表中的項目保持自己的特征和狀態(如 <input/> 中的輸入內容,<switch/> 的選中狀態),需要使用 wx:key 來指定列表中項目的唯一的標識符。

wx:key 的值以兩種形式提供

字符串,代表在 for 循環的 array 中 item 的某個 property,該 property 的值需要是列表中唯一的字符串或數字,且不能動態改變。

保留關鍵字 *this 代表在 for 循環中的 item 本身,這種表示需要 item 本身是一個唯一的字符串或者數字,如:

當數據改變觸發渲染層重新渲染的時候,會校正帶有 key 的組件,框架會確保他們被重新排序,而不是重新創建,以確保使組

件保持自身的狀態,并且提高列表渲染時的效率。

如不提供 wx:key,會報一個 warning, 如果明確知道該列表是靜態,或者不必關注其順序,可以選擇忽略。

示例代碼:

<switch wx:for="{{objectArray}}" wx:key="unique" style="display: block;"> {{item.id}} </switch><button bindtap="switch"> Switch </button><button bindtap="addToFront"> Add to the front </button><switch wx:for="{{numberArray}}" wx:key="*this" style="display: block;"> {{item}} </switch><button bindtap="addNumberToFront"> Add to the front </button>Page({ data: {  objectArray: [   {id: 5, unique: 'unique_5'},   {id: 4, unique: 'unique_4'},   {id: 3, unique: 'unique_3'},   {id: 2, unique: 'unique_2'},   {id: 1, unique: 'unique_1'},   {id: 0, unique: 'unique_0'},  ],  numberArray: [1, 2, 3, 4] }, switch: function(e) {  const length = this.data.objectArray.length  for (let i = 0; i < length; ++i) {   const x = Math.floor(Math.random() * length)   const y = Math.floor(Math.random() * length)   const temp = this.data.objectArray[x]   this.data.objectArray[x] = this.data.objectArray[y]   this.data.objectArray[y] = temp  }  this.setData({   objectArray: this.data.objectArray  }) }, addToFront: function(e) {  const length = this.data.objectArray.length  this.data.objectArray = [{id: length, unique: 'unique_' + length}].concat(this.data.objectArray)  this.setData({   objectArray: this.data.objectArray  }) }, addNumberToFront: function(e){  this.data.numberArray = [ this.data.numberArray.length + 1 ].concat(this.data.numberArray)  this.setData({   numberArray: this.data.numberArray  }) }})

這里寫下個人的理解,有什么不對的地方希望大家指正:以<switch></switch>為例,如果沒有wx:key,選中其中的某個按鈕的時候,改變其順序 或添加選項的時,選中的按鈕時不回跟隨 上個按鈕改變順序的,會一直在固定位子,如果如果有wx:key則相反,適用于列表或其他標簽可以改變順序或添加項目的情況

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 丰县| 新宁县| 驻马店市| 惠来县| 思南县| 福泉市| 乐至县| 贵南县| 陕西省| 分宜县| 林周县| 阿拉善左旗| 荆州市| 云和县| 嘉善县| 滦平县| 阿克陶县| 宿迁市| 永嘉县| 宁都县| 新民市| 恩施市| 广西| 临沭县| 酒泉市| 海安县| 肇源县| 蓬莱市| 岳池县| 日土县| 盐池县| 赤峰市| 任丘市| 筠连县| 四平市| 丰镇市| 昌乐县| 赣州市| 望江县| 庆云县| 广德县|