给出以下示例代码:
import { LitElement, html, css } from 'lit-element';
class ItemsDisplay extends LitElement {
static get styles() {...}
static get properties {...}
constructor () {
super();
...
}
render {
return html`
${this.items.map((item, index, array) => html`
<div class="name">
...
</div>
`)}
`;
}
}
选择类“name”的所有节点的适当方法是什么?
我尝试过以下方法,但是failed;一直nodesList
was undefined
:
this.nodesList = this.shadowRoot.querySelectorAll(".name");
firstUpdated(changedProperties) {
return this.nodesList = this.shadowRoot.querySelectorAll(".name");
}
getNodesList() {
let nodesList = this.shadowRoot.querySelectorAll(".name");
...
}
我也尝试过:
connectedCallback() {
super.connectedCallback();
return this.nodesList = this.shadowRoot.querySelectorAll(".name");
}
期待阅读解决方案。
Tia
您不应该尝试在构造函数中访问 DOM 节点,因为它们还不可用。
查询 DOM 节点的最佳位置是firstUpdated()
生命周期回调,在第一次更新元素的 DOM 后调用。您也不需要从以下位置返回它firstUpdated
,你可以这样做:
firstUpdated(changedProperties) {
// Store a reference to the form element for easy access
this.$someNode = this.shadowRoot.querySelector('div');
您可以在以下位置查看一些示例:https://stackblitz.com/edit/open-wc-lit-demos?file=02-intermediate%2F05-querying-dom.js https://stackblitz.com/edit/open-wc-lit-demos?file=02-intermediate%2F05-querying-dom.js
https://stackblitz.com/edit/open-wc-lit-demos?file=02-intermediate%2F01-first-updated.js https://stackblitz.com/edit/open-wc-lit-demos?file=02-intermediate%2F01-first-updated.js
此外,如果您使用 TypeScript,则可以使用query
装饰器:
@query('div')
myDiv;
更多信息:https://github.com/Polymer/lit-element/blob/master/src/test/lib/decorators_test.ts#L326 https://github.com/Polymer/lit-element/blob/master/src/test/lib/decorators_test.ts#L326
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)