LitElement 对象属性为 null

问题描述

我有一个将对象作为属性的组件,但由于某种原因,在呈现 this.item 时未定义。

@property({type: Object}) item?: {
    family: {iconUrl: string; name: string};
} | null;

static get styles(): CSSResult[] {
    return [
        css`
            ${unsafeCSS(styles)}
        `
    ];
}

render(): TemplateResult {
    if (this.item) { 
       return html`<div>found item</div>
     } else {
       return html`<div>item not found</div>
     }
}
 

在我的 HTML 中,我有以下内容

const item = {  
   family: {
      name: 'title',iconUrl: 'url'
   } 

}

html`<my-component item="${item}"></my-component>

为了接受一个对象作为参数,我有什么遗漏吗?我尝试调整了很多东西,例如使 arg .item="{ }" 无济于事。

解决方法

使用不带字符串引号的属性语法:

html`<my-component .item=${item}></my-component>`

您可以告诉 Lit 不检查字符串属性:

@property({attribute: false}) item?: {
    family: {iconUrl: string; name: string};
};

除非您想以不同于 null 的方式处理它,否则您不需要显式 undefined(如果您不设置它,则为默认设置)。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...