【问题标题】:Error when using unsafeHTML with lit-element将 unsafeHTML 与 lit-element 一起使用时出错
【发布时间】:2020-07-23 10:39:21
【问题描述】:

这是我的代码:

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 }); }

enter image description here

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

【问题讨论】:

  • 你提到的错误显示在指令的 in place 中,而不是在控制台中,不是吗?
  • 是的,它显示在渲染它的 DOM 中。

标签: javascript web-component lit-element lit-html


【解决方案1】:

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

$ npm dedupe

另外,对于纱线用户:

$ yarn install --flat

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

【讨论】:

  • 它有效,因为我重复从 lit-html 导入 unsafeHTML,我的朋友从另一个组件中包含一次,谢谢。
猜你喜欢
  • 1970-01-01
  • 2019-05-24
  • 1970-01-01
  • 2022-09-13
  • 2019-10-11
  • 1970-01-01
  • 2021-04-10
  • 2021-08-01
  • 1970-01-01
相关资源
最近更新 更多