有没有办法让 LitHtml 属性成为可选的?

Is there a way to make LitHtml attributes optional?

我不是在谈论布尔属性,如果你不想添加一个空的 class 属性,如 class 如果没有 CSS class .

html`<span class=${hasClass ? 'my-class' : ''}></span>`

有一个 ifDefined 指令可以满足您的需求。如果值为 undefined,则不会呈现该属性。

import {ifDefined} from 'lit-html/directives/if-defined';

html`<span class=${ifDefined(hasClass ? 'my-class' : undefined)}></span>`