Supersharp 的答案是正确的,但它不是 StencilJS 代码,而且主机上下文支持很不稳定(在 Firefox 中不起作用,可能在 IE11 中不起作用)。
您可以将属性“传输”到宿主元素,然后使用宿主组件样式内部的选择器:
TSX:
private intent: String;
componentWillLoad() {
this.intent = document.querySelector('html').getAttribute('data-whatintent');
}
hostData() {
return {
'data-whatintent': this.intent
};
}
SCSS:
:host([data-whatintent="keyboard"]) *:focus {
outline: solid 2px #1A79C6;
}
If the data-whatintent
属性动态更改,使其成为组件的属性,并让侦听器函数更新您的组件。您可以选择使用该属性向主机添加/删除类以进行样式设置,但您也可以继续使用属性选择器。
TSX:
@Prop({ mutable: true, reflectToAtrr: true }) dataWhatintent: String;
componentWillLoad() {
this.dataWhatintent = document.querySelector('html').getAttribute('data-whatintent');
}
hostData() {
return {
class: {
'data-intent-keyboard': this.dataWhatintent === 'keyboard'
}
};
}
SCSS:
:host(.data-intent-keyboard) *:focus {
outline: solid 2px #1A79C6;
}
文档的键盘和鼠标事件处理程序:
function intentHandler(event: Event) {
const intent = event instanceof KeyboardEvent ? 'keyboard' : 'mouse';
document.querySelectorAll('my-custom-component').forEach(
el => el.setAttribute('data-whatintent', intent)
);
}