HTML自定义组件可以简单的理解为自定义标签。
如何创建自定义组件
创建自定义组件只需要两步
第一,定义自定义组件
第二,注册自定义组件
看下面的例子
<!DOCTYPE html>
<html>
<body>
<!-- 使用自定义组件 -->
<custom-button>I am a custom button!</custom-button>
<script>
// 第一步:定义自定义按钮组件
class CustomButton extends HTMLElement {
//这里略. 下面单独说
}
// 第二步:注册自定义按钮组件
customElements.define('custom-button', CustomButton);
</script>
</body>
</html>
下面,我们再看看class CustomButton的实现
class CustomButton extends HTMLElement {
constructor() {
super();
// 创建 Shadow DOM
const shadow = this.attachShadow({ mode: 'open' });
// 创建按钮元素
const button = document.createElement('button');
button.innerText = this.textContent;
// 将按钮元素添加到 Shadow DOM 中
shadow.appendChild(button);
}
}
最后运行一下,在浏览器里的效果就是这样:
以后,你就可以在html里插入 <custom-button>button name</custom-button>来创建你自己的button. 当然,你可能会说,我直接写 <button type="button">Click Me!</button> 不比你自定义的button容易吗?是的,这是因为我们这里只是个demo,它很简单,以方便你理解怎么创建自定义组件。在真正的场景中,你自定义的button可能会有自己的样式,属性和行为,可能很复杂。把一个复杂的组件封装成一个标签,我们就可以很方便的重用它,代码也显得整洁。
这里面有一个重要概念是shadow dom,你可能不太理解。或许可以在以后的文章里单独讲它。