【问题标题】:Lit-element, how to concatenate TemplateResult?Lit-element,如何连接 TemplateResult?
【发布时间】:2021-07-29 00:47:58
【问题描述】:

我们有一个显示标题标题的自定义模板元素,我们希望扩展这个组件,以便在我们单击按钮时也显示带有面包屑的标题标题。

示例代码:

      ... private getTemplateResultFromProperty: TemplateResult[] = []; ...
        
            //This works fine: 
            func1(): TemplateResult {
            return html`  
                  <custom-header-template
                    .data=${data}'>
                </custom-header-template>` 
        }


                 //Can't return concatenated header  
                 func2(): TemplateResult {
                //repeat does not work, this returns empty strings
                    return html`${repeat(this.getTemplateResultFromProperty, t => t)}`;
            
                } 

我们只能在 func2 方法中返回并显示新的标头,方法是指定一个数组元素而不使用 html`` 像这样:return this.headerTemplateArray[1] 但这不是我们想要的做..

错误消息:Uncaught (in promise) TypeError: Cannot read property 'split' of null at new Template (template.js:87) 当我们尝试这个时:return html`${this.getTemplateResultFromProperty}`;

在这个方法中,html``方法似乎对我们根本不起作用...... 因此,我们怀疑我们使用 repeat() 的方式可能存在问题,或者我们以错误的方式连接/使用 TemplateResult。

有什么想法吗?

illustration

【问题讨论】:

  • 如果您在问题中添加带有 [ ] 按钮的代码 sn-p 会有所帮助,这样我们就可以运行代码

标签: web-component breadcrumbs lit-element lit-html lit


【解决方案1】:

lit-html 支持任何其他可渲染值的渲染数组,包括 TemplateResults。如果你不需要修改它,你应该能够返回数组,它确实已经是一个 TemplateResults 数组。

  func2(): Array<TemplateResult> {
    this.getTemplateResultFromProperty;
  } 

如果出于某种原因您需要将其放入单个 TemplateResult 用于其他一些非 lit-html 代码(我希望不是这种情况,如果是这样,也许您可​​以扩大您的类型),那么你可以只包装数组:

  func2(): TemplateResult {
    html`${this.getTemplateResultFromProperty}`;
  } 

如果这不起作用,那么我怀疑getTemplateResultFromProperty 实际上不是Array&lt;TemplateResult&gt;。既然看起来你已经尝试过了,你是否可以自省该变量以确保它确实是一个数组或可迭代的?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    • 1970-01-01
    • 2021-04-10
    • 2022-09-13
    • 1970-01-01
    • 2019-08-05
    • 2021-01-01
    相关资源
    最近更新 更多