如何在自定义元素中添加按钮点击事件

how to add a button click event in a custom element

我想给 ID 为 hamb-btn 的按钮添加一个点击事件,点击它会在 div class = "nav 中添加一个新的 class -link 显示”元素。例如,如果按下 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);

您始终可以对 Lit 组件中的动态样式使用 classMapstyleMap 指令。如需更多信息,请访问 Dynamic classes and 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-[=37= 更新 div ] 新班级名”