首页 > 解决方案 > 将 unsafeHTML 与 lit-element 一起使用时出错

问题描述

这是我的代码:

import {customElement, LitElement, html, property, css} from 'lit-element';
import {unsafeHTML} from 'lit-html/directives/unsafe-html.js';

@customElement('my-component')
export class myComponent extends LitElement {
  render() {
    const markup = '<div>Some HTML to render.</div>';
    return html`
      ${unsafeHTML(markup)}
    `;
  }
}

但是当我在浏览器上运行时,我收到如下错误:

part => { if (!(part instanceof NodePart)) { throw new Error('unsafeHTML can only be used in text bindings'); } const previousValue = previousValues.get(part); if (previousValue !== undefined && isPrimitive(value) && value === previousValue.value && part.value === previousValue.fragment) { return; } const template = document.createElement('template'); template.innerHTML = value; // innerHTML casts to string internally const fragment = document.importNode(template.content, true); part.setValue(fragment); previousValues.set(part, { value, fragment }); }

在此处输入图像描述

我的代码很简单,但我仍然遇到错误,所以任何人都可以向我建议如何使其工作。

标签: javascriptweb-componentlit-elementlit-html

解决方案


此类错误通常是由同一项目中多个版本的 lit-html 交互引起的。一个常见的场景是当您开始使用LitElement(内部使用 的版本lit-html)然后lit-html单独安装以便能够使用内置指令时。这有时会导致重复,可以通过运行轻松修复

$ npm dedupe

此外,对于纱线用户:

$ yarn install --flat

在这种情况下可以提供帮助。


推荐阅读