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

倾然丶 夕夏残阳落幕 提交于 2020-01-25 09:30:07

问题


Question is pretty much self-explanatory.

Example:

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

回答1:


There isn't one way to do specifically what you mention here, but there are two approaches that can get you somewhat close:

  • Conditional rendering

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>`;
  }
};
  • Using the unsafe html directive

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


来源:https://stackoverflow.com/questions/59259400/is-there-a-way-to-make-tags-in-lit-html-templates-dynamic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!