有没有办法让 lit-html 模板中的标签动态化?

Is there a way to make tags in lit-html templates dynamic?

问题几乎不言自明。

示例:

function generateTemplate(tag) {
  return html`
    <${tag}
      .some-prop=
    >
      ...
    </${tag}>
  `;
}

没有一种方法可以专门完成您在此处提到的操作,但有两种方法可以让您稍微接近:

  • 条件渲染

const template = tag => { 
  if (tag === 'custom-component') {
    return html`<custom-component></custom-component>`;
  } else if (tag === 'other-component') {
    return html`...`;
  } else {
    return html`<some-default></some-default>`;
  }
};

import {unsafeHTML} from 'lit-html/directives/unsafe-html.js';
const template = unsafeContent => {
  // bear in mind that this should only be done after sanitizing the content
  return html`${unsafeHTML(unsafeContent)}`;
};
template('<my-component>Some content</my-component>');