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