微信小程序自定義組件——接受外部傳入的樣式類


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM