自定义元素附带一组生命周期钩子。在本节中,你将使用其中两个:
constructorconnectedCallbackconstructor 在元素首次创建时调用:例如,通过调用 document.createElement('rating-element') 或 new RatingElement()。构造函数是设置元素的好地方。
在 constructor 中进行 DOM 操作是不好的做法。
这是因为 DOM 操作会减慢初始加载时间,并且在某些边界情况下会导致一些问题。
connectedCallback 在自定义元素附加到 DOM 时调用。这通常是进行初始 DOM 操作的地方。
现在,回到自定义元素,为其关联一些 DOM。在元素附加到 DOM 时设置其内容:
export class RatingElement extends HTMLElement { rating: number;
constructor() { super(); this.rating = 0; }
connectedCallback() { this.innerHTML = ` <style> rating-element { display: inline-flex; align-items: center; } rating-element button { background: transparent; border: none; cursor: pointer; } </style> <button class="thumb_down" > <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M15 3H6c-.83 0-1.54.5-1.84 1.22l-3.02 7.05c-.09.23-.14.47-.14.73v2c0 1.1.9 2 2 2h6.31l-.95 4.57-.03.32c0 .41.17.79.44 1.06L9.83 23l6.59-6.59c.36-.36.58-.86.58-1.41V5c0-1.1-.9-2-2-2zm4 0v12h4V3h-4z"/></svg> </button> <span class="rating">${this.rating}</span> <button class="thumb_up"> <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M1 21h4V9H1v12zm22-11c0-1.1-.9-2-2-2h-6.31l.95-4.57.03-.32c0-.41-.17-.79-.44-1.06L14.17 1 7.59 7.59C7.22 7.95 7 8.45 7 9v10c0 1.1.9 2 2 2h9c.83 0 1.54-.5 1.84-1.22l3.02-7.05c.09-.23.14-.47.14-.73v-2z"/></svg> </button> `; } }
customElements.define('rating-element', RatingElement); export class RatingElement extends HTMLElement { constructor() { super(); this.rating = 0; }
connectedCallback() { this.innerHTML = ` <style> rating-element { display: inline-flex; align-items: center; } rating-element button { background: transparent; border: none; cursor: pointer; } </style> <button class="thumb_down" > <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M15 3H6c-.83 0-1.54.5-1.84 1.22l-3.02 7.05c-.09.23-.14.47-.14.73v2c0 1.1.9 2 2 2h6.31l-.95 4.57-.03.32c0 .41.17.79.44 1.06L9.83 23l6.59-6.59c.36-.36.58-.86.58-1.41V5c0-1.1-.9-2-2-2zm4 0v12h4V3h-4z"/></svg> </button> <span class="rating">${this.rating}</span> <button class="thumb_up"> <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M1 21h4V9H1v12zm22-11c0-1.1-.9-2-2-2h-6.31l.95-4.57.03-.32c0-.41-.17-.79-.44-1.06L14.17 1 7.59 7.59C7.22 7.95 7 8.45 7 9v10c0 1.1.9 2 2 2h9c.83 0 1.54-.5 1.84-1.22l3.02-7.05c.09-.23.14-.47.14-.73v-2z"/></svg> </button> `; } }
customElements.define('rating-element', RatingElement);
在 constructor 中,你在元素上存储了一个名为 rating 的实例属性。在 connectedCallback 中,你向 <rating-element> 添加了 DOM 子节点来显示当前评分,以及点赞和踩按钮。
此示例未遵循控件和输入的无障碍最佳实践。