我們的組件有時(shí)候需要根據(jù)property的值來呈現(xiàn)不同效果。
例如當(dāng)isActive
是true的時(shí)候,使用active
樣式。一個(gè)比較傳統(tǒng)的方法是每當(dāng)isActive
改變的時(shí)候添加/刪除active
樣式:
/* css */
.active {
color: yellow;
background: black;
}
// js
properties {
isActive: {
type: Boolean,
notify: true,
observer: '_observeIsActive'
}
},
_observeIsActive() {
if (this.isActive) {
this.classList.add('active');
} else {
this.classList.remove('active');
}
}
實(shí)際上polymer能提供一個(gè)更方便的解決。
使用reflectToAttribute
詳細(xì)可查看文檔Reflecting properties to attributes
Polymer的property提供一個(gè)reflectToAttribute
設(shè)置,來將property反射到元素的html(attribute)上。當(dāng)你的<my-element>
的isActive
的reflectToAttribute
設(shè)置為true,而isActive
的值也為true的時(shí)候,瀏覽器的DOM會(huì)變成這樣:
<my-element is-active></my-element>
通過這么個(gè)特性,我們就可以簡化上面的功能的實(shí)現(xiàn)了:
/* 直接去掉之前的.active,根據(jù)元素的attribute里是否包含'is-active'來顯示樣式 */
:host[is-active] {
color: yellow;
background: black;
}
properties {
isActive: {
type: Boolean,
notify: true,
// 不再需要observer,但需要將property反射到attribute上
reflectToAttribute: true
}
}