[英]How to add an event handler to an element which is rendered on a button click?
[英]how to add a button click event in a custom element
我想向 id 為 hamb-btn 的按鈕添加一個點擊事件,當點擊它時,它將在 div class = "nav-link show" 元素中添加一個新的 class。 如果按下 hamb 按鈕,就像這樣是添加 class 的示例。 這是我的代碼...注意:我使用 webpack。
import { html, css, LitElement } from 'lit-element'; class SinDrawer extends LitElement { static get styles() { return css` nav { display: flex; padding: 8px; background-color: var(--main-color); } `; } constructor() { super(); } render() { return html` <nav> <div class="nav-brand"> <a href="#/home"> <img src="./icons/icon_512.png" alt="sr-brand" height="50" title="Sinfor-Resto"> </a> </div> <div class="nav-link"> <a href="#/home" class="nav-anchor">Beranda</a> <a href="#/favorite" class="nav-anchor">Favorite</a> <a href="#/about" class="nav-anchor">Tentang</a> </div> <button id="hamb-btn" onclick="">☰</button> </nav> `; } } customElements.define('sin-drawer', SinDrawer);
您始終可以使用classMap
或styleMap
指令來實現 Lit 組件中的動態樣式。 更多信息可在動態類和 styles中獲得。
import { html, css, LitElement } from 'lit-element';
import { classMap } from 'lit/directives/class-map.js';
class SinDrawer extends LitElement {
static get styles() {
return css`
nav {
display: flex;
padding: 8px;
background-color: var(--main-color);
}
`;
}
static get properties() {
return {
_show: { state: true },
};
}
constructor() {
super();
this._show = false;
}
show() {
this._show = !this._show;
}
render() {
return html`
<nav>
<div class="nav-brand">
<a href="#/home">
<img src="./icons/icon_512.png" alt="sr-brand" height="50" title="Sinfor-Resto" />
</a>
</div>
<div class="nav-link ${classMap({ show: this._show })}">
<a href="#/home" class="nav-anchor">Beranda</a>
<a href="#/favorite" class="nav-anchor">Favorite</a>
<a href="#/about" class="nav-anchor">Tentang</a>
</div>
<button id="hamb-btn" @click=${this.show}>☰</button>
</nav>
`;
}
}
customElements.define('sin-drawer', SinDrawer);
這可以通過 3 個簡單的步驟完成。
static get properties(){
return{
newClass: String
}
}
<div class="nav-link ${this.newClass}">
<button id="hamb-btn" @click=${e=>this.newClass =”newClassName”}>☰</button>
由於 this.newClass 被添加到元素的屬性中,它將重新渲染 DOM 並使用 class=”nav-link newClassName” 更新 div
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.