https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/wxml-wxss.html
外部樣式類
有時,組件希望接受外部傳入的樣式類。此時可以在 Component
中用 externalClasses
定義段定義若干個外部樣式類。這個特性從小程序基礎庫版本 1.9.90 開始支持。
這個特性可以用於實現類似於 view
組件的 hover-class
屬性:頁面可以提供一個樣式類,賦予 view
的 hover-class
,這個樣式類本身寫在頁面中而非 view
組件的實現中。
注意:在同一個節點上使用普通樣式類和外部樣式類時,兩個類的優先級是未定義的,因此最好避免這種情況。
代碼示例:
/* 組件 custom-component.js */ Component({ externalClasses: ['my-class'] })
<!-- 組件 custom-component.wxml --> <custom-component class="my-class">這段文本的顏色由組件外的 class 決定</custom-component>
這樣,組件的使用者可以指定這個樣式類對應的 class ,就像使用普通屬性一樣。在 2.7.1 之后,可以指定多個對應的 class 。
代碼示例:
<!-- 頁面的 WXML --> <custom-component my-class="red-text" /> <custom-component my-class="large-text" /> <!-- 以下寫法需要基礎庫版本 2.7.1 以上 --> <custom-component my-class="red-text large-text" />
.red-text { color: red; } .large-text { font-size: 1.5em; }