[英]“shadowRoot.querySelector” not working with lit-element in Web Components
Ok, so I saw some similar problems to mine here but none of the solutions worked for me so I think it's better to describe my problem more specifically.好的,所以我在这里看到了一些与我类似的问题,但没有一个解决方案对我有用,所以我认为最好更具体地描述我的问题。
I'm working with web components and at first I was not using lit element, at that time the this.shadowRoot.querySelector('button')
was working just fine, but now that i'm using lit element this selector always returns null, this is my code:我正在使用 web 组件,起初我没有使用 lit 元素,当时
this.shadowRoot.querySelector('button')
工作得很好,但现在我使用的是 lit 元素,这个选择器总是返回 null ,这是我的代码:
static get styles(){
return css`
button{
color: #737373;
padding: 15px 30px;
font-size: 16px;
}
.primary{
border-radius: 25px;
border: 1px solid;
color: #4386ff;
transition: 0.3s;
}
.disabled {
pointer-events: none;
color: #cacaca;
background-color: #fff;
}
`;
}
static get properties(){
return{
type: { type: String },
text: { type: String},
fullSize: { type: Boolean},
disabled: { type: Boolean}
};
}
constructor() {
super();
this.type = "primary";
this.text = "Seguir";
this.disabled = false;
this.fullSize = false;
this.el = this.shadowRoot.querySelector('button');
if (this.hasAttribute('disabled')) {
this.el.classList.add('disabled');
}
}
render () {
return html`
<button class="${this.type}"
?fullSize="${this.fullSize}"
?disabled="${this.disabled}"
>${this.text}</button>
`;
}
} }
That way the this.shadowRoot.querySelector('button')
always returns null?!这样
this.shadowRoot.querySelector('button')
总是返回 null?! should I use some lifecycle method to make it work?我应该使用一些生命周期方法来使其工作吗? I tried
updated
but it also didn't work.我尝试
updated
但它也没有工作。
My HTML component is like this:我的 HTML 组件是这样的:
<default-button type="secondary" text="Salvar" fullSize></default-button>
Ok, I read some other stuff about lifecycle and now i understand about the element still beeing built when i first tried to call it, now using the firstUpdated()
method it works!好的,我阅读了一些关于生命周期的其他内容,现在我了解了当我第一次尝试调用它时仍在构建的元素,现在使用
firstUpdated()
方法它可以工作! Thanks!谢谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.