微信小程序 抽象節(jié)點

2020-07-31 13:35 更新

抽象節(jié)點

這個特性自小程序基礎(chǔ)庫版本 1.9.6 開始支持。

在組件中使用抽象節(jié)點

有時,自定義組件模板中的一些節(jié)點,其對應(yīng)的自定義組件不是由自定義組件本身確定的,而是自定義組件的調(diào)用者確定的。這時可以把這個節(jié)點聲明為“抽象節(jié)點”。

例如,我們現(xiàn)在來實現(xiàn)一個“選框組”(selectable-group)組件,它其中可以放置單選框(custom-radio)或者復(fù)選框(custom-checkbox)。這個組件的 wxml 可以這樣編寫:

代碼示例:

<!-- selectable-group.wxml -->
<view wx:for="{{labels}}">
  <label>
    <selectable disabled="{{false}}"></selectable>
    {{item}}
  </label>
</view>

其中,“selectable”不是任何在 json 文件的 usingComponents 字段中聲明的組件,而是一個抽象節(jié)點。它需要在 componentGenerics 字段中聲明:

{
  "componentGenerics": {
    "selectable": true
  }
}

使用包含抽象節(jié)點的組件

在使用 selectable-group 組件時,必須指定“selectable”具體是哪個組件:

<selectable-group generic:selectable="custom-radio" />

這樣,在生成這個 selectable-group 組件的實例時,“selectable”節(jié)點會生成“custom-radio”組件實例。類似地,如果這樣使用:

<selectable-group generic:selectable="custom-checkbox" />

“selectable”節(jié)點則會生成“custom-checkbox”組件實例。

注意:上述的 custom-radio 和 custom-checkbox 需要包含在這個 wxml 對應(yīng) json 文件的 usingComponents 定義段中。

{
  "usingComponents": {
    "custom-radio": "path/to/custom/radio",
    "custom-checkbox": "path/to/custom/checkbox"
  }
}

抽象節(jié)點的默認(rèn)組件

抽象節(jié)點可以指定一個默認(rèn)組件,當(dāng)具體組件未被指定時,將創(chuàng)建默認(rèn)組件的實例。默認(rèn)組件可以在 componentGenerics 字段中指定:

{
  "componentGenerics": {
    "selectable": {
      "default": "path/to/default/component"
    }
  }
}

提示:

  • 節(jié)點的 generic 引用 generic:xxx="yyy" 中,值 yyy 只能是靜態(tài)值,不能包含數(shù)據(jù)綁定。因而抽象節(jié)點特性并不適用于動態(tài)決定節(jié)點名的場景。


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號