我正在学习如何使用自定义 Web 组件。我尝试使用自定义组件创建一个表行。这是 HTML:
<table border="2">
<tbody>
<table-row></table-row>
<table-row></table-row>
</tbody>
</table>
这是 JavaScript:
// Create a class for the element
class TableRow extends HTMLElement {
constructor() {
// Always call super first in constructor
super();
}
connectedCallback() {
let tr = document.createElement('tr')
let td = document.createElement('td')
td.textContent = "Row content";
tr.append(td);
this.append(tr);
}
}
customElements.define("table-row", TableRow);
这是一个 JSFiddle:https://jsfiddle.net/Imabot/c92fye8d/1/
如您所见,它没有按预期工作。
我做错了什么吗?
一般来说,构建自定义组件时,我们应该填充还是替换自定义标签
<table-row></table-row>
?
// Create a class for the element
class TableRow extends HTMLElement {
constructor() {
// Always call super first in constructor
super();
}
connectedCallback() {
let tr = document.createElement('tr')
let td = document.createElement('td')
td.textContent = "Row content";
tr.append(td);
this.append(tr);
}
}
customElements.define("table-row", TableRow);
<table border="2">
<tbody>
<table-row></table-row>
<table-row></table-row>
</tbody>
</table>
您不能在表格中使用自定义标签,也不建议这样做。
您可以做的是将 a 定义为自定义行,如下例所示:
class CustomTableRow extends HTMLTableRowElement {
constructor() {
super(); // Always call super first in constructor
// Your custom initialization
}
connectedCallback() {
let td = document.createElement('td');
td.textContent = "Row content";
this.appendChild(td);
}
}
customElements.define('custom-table-row', CustomTableRow, { extends: 'tr' });
<table border="2">
<tbody>
<tr is="custom-table-row"></tr>
<tr is="custom-table-row"></tr>
</tbody>
</table>