对于像我这样疯狂的人,由于各种原因不希望使用自定义元素,有没有办法访问与templateResult相关的DOM?
我尝试在渲染之前修改templateResult的内容但没有成功......我也查看了templateFactory,但似乎它被设计为最终(父)templateResult呈现给容器,而不是嵌套的templateResults。
const componentA = {
id: 'comp-a',
template(){ return html`<div>No ID yet</div>` }
};
const app = {
template(){
const tmpl = html`<main><div>${ componentA.template() }</div></main>`
// here: use componentA.id to set top element's id
// seems it's too late to change the template, DOM is already created?
// so how to get a reference to the created DOM from a templateResult?
return tmpl
}
};
render( app.template(), document.body);
例如,如何从其id中自动在componentA的top元素上设置id?
问题是lit-html
实际上创建了TemplateResult
s,它只是在调用render()
时将创建的HTML的表示。
在这个意义上,A模板中的<div>
对于代表它的TemplateResult
没有特别的“意义”,但它的实例仍然可以通常从渲染容器中进行querySelect
ed。
const tmpl = html`
<main>
<div>
${componentA.template()} <!-- This returns a TemplateResult -->
</div>
</main>
`;
你仍然完全被允许为<div>
分配一个id:
const componentA = {
// ...
template() {
return html`
<div id="comp-a"></div>
`;
}
}
如果只想在稍后阶段分配id,可以将其作为参数传递给创建A模板的函数:
const componentA = {
// ...
template(id) {
return html`
<div id=${id}></div>
`;
}
}