Custom Elements
一句话解释
Custom Elements 是浏览器 API,通过 JavaScript 类注册带自定义行为的新 HTML 元素类型。
用大白话说
Custom Elements API 让你定义全新的 HTML 标签。你写一个继承 HTMLElement(或特定内置元素如 HTMLButtonElement)的类,用 customElements.define('my-tag', MyClass) 注册,然后在 HTML 任意位置使用 <my-tag>——它会被实例化并运行你类的生命周期方法。生命周期回调有 connectedCallback(加入 DOM)、disconnectedCallback(移除)、attributeChangedCallback(被观察的属性变化)和 adoptedCallback(移至新文档)。它们对应 React 的挂载/卸载/更新生命周期,但在平台层面。Custom Elements 可为自主型(全新标签)或自定义内置型(扩展已有标签如 <button is="my-button">)。结合 Shadow DOM 与模板,它们构成无框架可复用 UI 的 Web Components 标准。
示例
javascript
class CountdownTimer extends HTMLElement {
static observedAttributes = ["seconds"];
connectedCallback() {
let n = Number(this.getAttribute("seconds"));
this.render = () => { this.textContent = `${n}s`; };
this.render();
this.timer = setInterval(() => { if (--n <= 0) clearInterval(this.timer); this.render(); }, 1000);
}
disconnectedCallback() { clearInterval(this.timer); }
}
customElements.define("countdown-timer", CountdownTimer);
// <countdown-timer seconds="10"></countdown-timer>类定义生命周期回调。connectedCallback 启动定时器;disconnectedCallback 清理。该标签像内置元素一样工作。
相关术语
相关资源
相关课程
- Web Components
Custom Elements 定义新标签。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。