[英]How to get a reference to the created DOM from a templateResult (not using custom elements)
對於像我這樣由於各種原因而不想使用自定義元素的那些瘋狂的人,有沒有辦法訪問與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的頂部元素上設置一個id?
事實是, lit-html
實際上創建了TemplateResult
,它們只是HTML的表示形式,一旦render()
被調用,就會創建該HTML。
在這種意義上,A模板中的<div>
相對於表示它的TemplateResult
沒有特定的“含義”,但是其實例通常仍可以從渲染容器中進行querySelect
。
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>
`;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.