有时候我们有这一种需求:在使用组件的时候,希望能传入自己写的class样式。
测试了一番,直接传递class参数是无效的,那我们怎么做呢?
开始实践
仔细查阅了官方文档,发现是可以的。
我们首先在组件的js文件中加入externalClasses数组变量,用于定义我们要传递的父层class名称:
/* 组件 index.js */
Component({
options: {
addGlobalClass: true
},
externalClasses: ['custom-class'],
properties: {
info: null,
name: String,
size: String,
color: String
},
methods: {
onClick() {
this.triggerEvent('click');
}
}
});
然后,组件的wxml中使用class="my-class"来使父层样式生效:
<!-- 组件 index.wxml -->
<view class="custom-class {{name}} iconfont" style="{{ color ? 'color: ' + color : '' }}; {{ size ? 'font-size: ' + size : '' }}" bind:tap="onClick">
</view>
<!-- index.wxss -->
@font-face {
font-family: "iconfont";
src: url('iconfont.eot?t=1556422480839'); /* IE9 */
src: url('iconfont.eot?t=1556422480839#iefix') format('embedded-opentype'),
/* IE6-IE8 */ url('data:application/x-font-woff2;charset=utf-8;base64,d09GMgABAAAAAAMEAAsAAAAABtQAAAK4AAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHEIGVgCCcAqBYIFQATYCJAMICwYABCAFhG0HMBv2BcgOJQWJ2IAhDiNAPDyt/e/c2fmqScSzeDIskUmWIb0KnvBGhJA8VNGQPPS3P/lXvn+Aqjlp2R3sjzcLz86pg1QJkYoGLFMmZbqUV8Yn7p3+FlAg8wHlNMfif1GAgaUBjbWpi6SAsGHsApdwnECjATmE3aqGDvCTWeMCcdlkEMEvF5Jllq0XamuWZvFAjfp0M/3A/fD38d9K+JHUFKy6k0uVCpT88rLzikpZcdEniOdzgK2iwByQiXO1qSOegjE9Naa8jIB9VQe/cln6FrHXP0/UsiqbQR8U3ZPYldxqZQI5bj8Ezoz6KGk51nZ9LwhPX698iIOp25SAd58HiumXq3eQKuOBwosft38NC7z9SKjo8vzj2o3LmIPTWEM2non7x7fsGnqwEqXs7TkQdB1PIv+vf+95Fa6Dvw90vv3hcYm68P6Ilk9LMT3l9v7ytKWv9Q/beqquygzb0ksQ9uE09/aZ9Fj/8dnQrarr1f1D13zCfLqq4ww2gbJaPs0exfm/ep4L1zqvh0MLHuubMvj5v6QFy/p5QP253cE/VOZZiKpMl1qmlFVTWUWe5HCUIwEF3Ktk+Tr9GavrueFcqNdz2546/SkK9cYomTGHGk3WUKveBhrNql7dpAvjKXIDZswDhHbPkbT6gEK7n5TM+I0avf6hVnt4otGFiNyyyUSYAsoZihwVIk0Sk+ywU8fKA6LqNjSMWkWWlYasLmRuU5RoVZpithrtyOaY4R4z6DinhDKHjVSB09BqdRAnc5hR5ioj5848tZrWvUklO2wQYAeDRBxSEJJJhInMwY76rbmA0vfbIINRViLWQqrxd0GMm6lzQktF04NSrbL3It3LK25jDHQ4jiIoxsGGqAIOZLVTDoSzfpAZknEqxhEJpzxq1Iz2VanW19g+oJA1YOlT2P0KtdfRZhLtAA==') format('woff2'),
url('iconfont.woff?t=1556422480839') format('woff'),
url('iconfont.ttf?t=1556422480839') format('truetype'),
/* chrome,
firefox,
opera,
Safari,
Android,
iOS 4.2+ */ url('iconfont.svg?t=1556422480839#iconfont') format('svg'); /* iOS 4.1- */
}
.iconfont {
font-family: "iconfont" !important;
font-size: 16px;
font-style: normal;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.icon-yemian:before {
content: "\e604";
}
最后,我们在页面中使用组件的时候,直接用my-class传递页面的wxss样式名称就好:
<!-- index.wxss -->
<ss-icon name="icon-yemian" size='30' color='#000' my-class="在这里写你的class" />