有人能告诉我为什么不能在lit的html
方法中使用变量吗?
const h1 = 'h1';
return html`
<${h1} class="a-heading ${classes}">
<slot></slot>
</${h1}>
`;
如果我用${h1}
替换为h1
,那就没有问题了。
发布于 2020-01-10 14:12:07
对于所有对我的解决方案感兴趣的人:如果可能的话,使用unsafeHTML
(如果您在其中包装任何输入字段,就不应该这样做)。
import { unsafeHTML } from 'lit-html/directives/unsafe-html';
// ...
const template = `
<h${this.rank} class="a-heading">
<slot></slot>
</h${this.rank}>
`;
return html`
${unsafeHTML(template)}
`;
发布于 2020-01-21 02:15:33
lit-html
不允许动态标记名的原因是lit可以用特殊标记替换表达式,然后用结果创建<template>
元素。
这里的关键和稍微微妙的部分是,它不使用值来创建模板。它们在模板被克隆之后,即HTML解析之后,被插入到模板中。没有办法进入DOM树并更改一个元素的标记名。我们必须移除元素,替换它,设置任何绑定,并将任何子元素移动到新元素中。这个会很贵的。
我们确实有计划支持静态绑定(一旦我们可以放弃对不完全实现模板文本的旧边缘浏览器的支持),在创建HTML <template>
之前对这些浏览器进行内插,这将允许对标记名使用表达式。但是,静态绑定不能用新数据更新--模板创建时的值是唯一使用的值。
发布于 2022-10-16 16:01:08
它是2022年,解决方案存在(从2020年年底- 问题)。
现在您可以使用https://lit.dev/docs/templates/expressions/#static-expressions中的某些内容
literal
模板。
您必须导入特殊版本的html
并使用literal
模板。import {html, literal} from 'lit/static-html.js';
@customElement('my-button')
class MyButton extends LitElement {
tag = literal`button`;
activeAttribute = literal`active`;
@property() caption = 'Hello static';
@property({type: Boolean}) active = false;
render() {
return html`
<${this.tag} ${this.activeAttribute}?=${this.active}>
<p>${this.caption}</p>
</${this.tag}>`;
}
}
然后
@customElement('my-anchor')
class MyAnchor extends MyButton {
tag = literal`a`;
}
literal
装饰的东西,你可以使用unsafeStatic
。
同样,您必须导入html
的特殊版本,然后使用unsafeStatic
函数。import {html, unsafeStatic} from 'lit/static-html.js';
@customElement('my-button')
class MyButton extends LitElement {
@property() caption = 'Hello static';
@property({type: Boolean}) active = false;
render() {
// These strings MUST be trusted, otherwise this is an XSS vulnerability
const tag = getTagName();
const activeAttribute = getActiveAttribute();
return html`
<${unsafeStatic(tag)} ${unsafeStatic(activeAttribute)}?=${this.active}>
<p>${this.caption}</p>
</${unsafeStatic(tag)}>`;
}
}
https://stackoverflow.com/questions/59666518
复制相似问题