如何将整个字符串作为属性/道具应用于Lit web组件



我有一个基本的Text Lit web组件,带有红色,用于的样式

import { LitElement, html } from "lit";
import { customElement } from "lit/decorators.js";
@customElement("bb-text")
export class Text extends LitElement {
render() {
return html` <p style="color: red;"><slot></slot></p> `;
}
}

我想把整个样式属性作为字符串传递,就像一样

import { LitElement, html } from "lit";
import { customElement } from "lit/decorators.js";
function getStyle() {
return 'style="color: red;"';
}
@customElement("bb-text")
export class Text extends LitElement {
render() {
return html` <p ${getStyle()}><slot></slot></p> `;
}
}

我尝试过的

  1. unsafeHTML:甚至不呈现组件

    return html` <p ${unsafeHTML(getStyle())}><slot></slot></p> `;
    
  2. 自定义指令:不执行

    import { LitElement, html } from "lit";
    import { customElement } from "lit/decorators.js";
    import { Directive, directive } from "lit/directive.js";
    class StyleDirective extends Directive {
    render() {
    return 'style="color: red;"';
    }
    }
    const getStyle = directive(StyleDirective);
    @customElement("bb-text")
    export class Text extends LitElement {
    render() {
    return html` <p ${getStyle()}><slot></slot></p> `;
    }
    }
    

Lit关于元素表达式的文档暗示它应该是可能的

html`<div ${myDirective()}></div>`

您需要为此使用静态表达式。

import { html, unsafeStatic } from "lit/static-html.js";
import { LitElement } from "lit";
import { customElement } from "lit/decorators.js";
function getStyle() {
return 'style="color: red;"';
}
@customElement("bb-text")
export class Text extends LitElement {
render() {
return html` <p ${unsafeStatic(getStyle())}><slot></slot></p> `;
}
}

最新更新