好的,所以我在这里看到了一些与我的问题类似的问题,但没有一个解决方案对我有用,所以我认为最好更具体地描述我的问题。
我正在使用 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>
`;
}
这样 this.shadowRoot.querySelector('button')
总是返回 null!!
我应该使用一些生命周期方法来让它工作吗?我尝试了 updated
但它也没有用。
我的 HTML 组件是这样的:
<default-button type="secondary" text="Salvar" fullSize></default-button>
最佳答案
好的,我阅读了一些关于生命周期的其他内容,现在我了解了当我第一次尝试调用它时仍在构建的元素,现在使用 firstUpdated()
方法它可以工作!谢谢!
关于javascript - "shadowRoot.querySelector"无法在 Web 组件中使用 lit-element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65010983/