[英]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.