字節(jié)跳動(dòng)小程序開發(fā)框架 抽象節(jié)點(diǎn)

2019-08-07 09:34 更新

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

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

在 selectable-group.ttml 中:

<view :for="{{ labels }}">
  <label>
    <selectable disabled="{{ false }}"></selectable>
    {{ item }}
  </label>
</view>

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

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

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


在使用 selectable-group 組件時(shí),必須指定 selectable 具體是哪個(gè)組件:

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

這樣,在生成這個(gè) selectable-group 組件的實(shí)例時(shí),selectable 節(jié)點(diǎn)會(huì)生成 custom-radio 組件實(shí)例。類似地,如果這樣使用:

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

selectable 節(jié)點(diǎn)則會(huì)生成 custom-checkbox 組件實(shí)例。

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

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

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


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

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

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


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

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號