【问题标题】:Rendering child elements with LitElement ( light DOM and slots )使用 LitElement 渲染子元素(轻 DOM 和插槽)
【发布时间】:2021-03-19 07:15:10
【问题描述】:

我正在尝试编写一个将包装未知子内容的 LitElement Web 组件。我读过有关插槽(https://lit-element.readthedocs.io/en/v0.6.4/docs/templates/slots/)的信息,但它似乎只适用于影子 DOM。我正在使用轻型 DOM。在 React 中,属性带有一个特殊的 'children' 属性来渲染子树。但是如何在 Light DOM 中的 LitElement 中实现这一点呢?尽管上面的文档谈到了轻 DOM,但在我的情况下它不起作用。

更新:我通过向我的元素添加“TemplateResult”类型的属性并将内容作为属性传递来解决这个问题。但不确定这是最好的解决方案。

【问题讨论】:

标签: children lit-element slot


【解决方案1】:

要在 Lit 版本 2 中直接在 DOM 树(又名 light-dom)中渲染元素,请使用从 lit/html.js 导出的 render(lit 从它的 lit-html 版本导入它,有关详细信息,请参阅 https://lit.dev/):

<script type=module>
// or from 'lit' and 'lit/html.js' respectively:
import { LitElement, html } from 'https://unpkg.com/lit?module';
import { render } from 'https://unpkg.com/lit/html.js?module';

class EgTime extends LitElement{
    connectedCallback(){
        super.connectedCallback();
        render(this.time(), this);
    }
    time(){
        const now = new Date();
        return html`<time datetime="${ now.toISOString() }">time ${ now.toLocaleTimeString() } ${ now.toLocaleDateString() }</time>`;
    }
    render(){
        return html`<hr> ::slotted( <slot>~~~</slot> ) <hr>`;
    }
}

customElements.define('eg-time', EgTime);
</script>
<eg-time style="position:fixed;inset:auto 3rem 3rem auto;background:#fff;padding:1rem;border:1px solid #000;">
...
</eg-time>

【讨论】:

    【解决方案2】:

    在 light Dom 中,您的 render() 将修改您的组件在安装之前的先前子节点。

    一种方法可以保存调用 connectedCallback 之前的任何内容。

    考虑以下示例

    export class Text extends LitElement {
      createRenderRoot() {
        return this;
      }
    
      connectedCallback() {
        super.connectedCallback();
        this._textOverride = this.innerText.trim();
      }
      render() {
        return html`
          <strong>${this._textOverride}</strong>
        `;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-07-12
      • 1970-01-01
      • 1970-01-01
      • 2020-08-20
      • 2021-07-21
      • 2020-06-03
      • 2018-01-09
      • 2019-12-11
      • 1970-01-01
      相关资源
      最近更新 更多