欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

微信小程序 wx:key詳細(xì)介紹

 更新時(shí)間:2016年10月28日 14:30:05   投稿:lqh  
這篇文章主要介紹了微信小程序 wx:key詳細(xì)介紹的相關(guān)資料,并附簡(jiǎn)單代碼實(shí)例,幫助大家學(xué)習(xí)理解,需要的朋友可以參考下

微信小程序 wx:key 在自己學(xué)習(xí)的時(shí)候不是多明白到底是怎么回事,經(jīng)過(guò)上網(wǎng)查閱資料,整理下:

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

wx:key

如果列表中項(xiàng)目的位置會(huì)動(dòng)態(tài)改變或者有新的項(xiàng)目添加到列表中,并且希望列表中的項(xiàng)目保持自己的特征和狀態(tài)(如 <input/> 中的輸入內(nèi)容,<switch/> 的選中狀態(tài)),需要使用 wx:key 來(lái)指定列表中項(xiàng)目的唯一的標(biāo)識(shí)符。

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

字符串,代表在 for 循環(huán)的 array 中 item 的某個(gè) property,該 property 的值需要是列表中唯一的字符串或數(shù)字,且不能動(dòng)態(tài)改變。

保留關(guān)鍵字 *this 代表在 for 循環(huán)中的 item 本身,這種表示需要 item 本身是一個(gè)唯一的字符串或者數(shù)字,如:

當(dāng)數(shù)據(jù)改變觸發(fā)渲染層重新渲染的時(shí)候,會(huì)校正帶有 key 的組件,框架會(huì)確保他們被重新排序,而不是重新創(chuàng)建,以確保使組

件保持自身的狀態(tài),并且提高列表渲染時(shí)的效率。

如不提供 wx:key,會(huì)報(bào)一個(gè) warning, 如果明確知道該列表是靜態(tài),或者不必關(guān)注其順序,可以選擇忽略。

示例代碼:

<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
  })
 }
})

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

感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!

相關(guān)文章

最新評(píng)論