首页 > 解决方案 > 如何在 hyperHTML 中动态更改标签

问题描述

此代码不起作用。

const render = ({title, tag, values}) => {
    bind(document.body)`
        <h1>${title}</h1>
        <div>
            <${tag} data=${values}></${tag}>
        </div>
    `
}

render({title: "test", tag: "custom-elem1", values: {foo: "bar"}})

我可以使用 hyperHTML 动态更改标签吗?

标签: javascripthyperhtml

解决方案


你可能不喜欢这个答案,但,你不能。

原因是hyperHTML与任何其他类似的库一样,不适用于字符串,它适用于 DOM,并且在 DOM 世界中,即使您尝试,也无法更改标签名称。

var div = document.createElement('div');
div.tagName = 'P';
console.log(div.tagName); // "DIV"

相反,您可以做的是返回您喜欢的元素。

const render = ({title, tag, values}) => {
  const ref = document.body;
  bind(ref)`
    <h1>${title}</h1>
    <div>${(() => {
      switch tag:
        case 'custom-elem1':
          return wire(ref)`<custom-elem1 data=${values} />`;
        case 'custom-elem2':
          return wire(ref)`<custom-elem2 data=${values} />`;
        case 'custom-elem3':
          return wire(ref)`<custom-elem3 data=${values} />`;
      })()
    }</div>`;
};

在这种情况下,你可以做任何你想做的事,只要你不会试图动态改变 DOM 标签的性质,因为即使是hyperHTML也做不到


推荐阅读