簡體   English   中英

如何在自定義元素中添加按鈕單擊事件

[英]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="">&#9776;</button> </nav> `; } } customElements.define('sin-drawer', SinDrawer);

您始終可以使用classMapstyleMap指令來實現 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}>&#9776;</button>
      </nav>
    `;
  }
}

customElements.define('sin-drawer', SinDrawer);

這可以通過 3 個簡單的步驟完成。

  1. 如下添加屬性'newClass'並在構造函數中將this.newClass初始化為“”。
     static get properties(){
        return{
             newClass: String
            }
        }   
  1. 將“newClass”添加到 div,如下所示
 <div class="nav-link ${this.newClass}">
  1. 單擊按鈕后,this.newClass 將包含新的 class 名稱。
<button id="hamb-btn" @click=${e=>this.newClass =”newClassName”}>&#9776;</button>

由於 this.newClass 被添加到元素的屬性中,它將重新渲染 DOM 並使用 class=”nav-link newClassName” 更新 div

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM