问题描述
我有一个将对象作为属性的组件,但由于某种原因,在呈现 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>
}
}
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
(如果您不设置它,则为默认设置)。