javascript - 如何在 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 动态更改标签吗?
解决方案
你可能不喜欢这个答案,但不,你不能。
原因是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也做不到
推荐阅读
- sql - 如何将不同日期的重复条目计为单个条目?
- javascript - Javascript。如何创建一个创建对象的循环,然后将这些对象推入数组?
- javascript - 使用 JavaScript 将数据插入数据库时,控制台中会创建错误“超出最大调用堆栈大小”
- javascript - 如何在反应中将句柄更改添加到待办事项应用程序?
- javascript - 无法在模板文字中调用函数
- bash - 如何将 sed 命令应用于匹配的模式文本并在文件中替换?
- html - 使 DIV 响应式地从内联块变为“偏移堆栈”
- elasticsearch - 替换字段中的坏词并将结果保存回字段而不索引该字段
- django - Django 模型 - 在 Django ORM 上建模(Postgres-12 数据库视图)
- python - 将 3 个数组相乘以形成一个 3D 数组,其中条目相乘