[英]how to add a button click event in a custom element
I want to add a click event to the button with id: hamb-btn, where when clicked it will add a new class in the div class = "nav-link show" element.我想向 id 为 hamb-btn 的按钮添加一个点击事件,当点击它时,它将在 div class = "nav-link show" 元素中添加一个新的 class。 like that is an example of adding the class if the hamb button is pressed.如果按下 hamb 按钮,就像这样是添加 class 的示例。 its my code... note: i use webpack.这是我的代码...注意:我使用 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);
You can always use classMap
or styleMap
directives for the dynamic styling in the Lit Component.您始终可以使用classMap
或styleMap
指令来实现 Lit 组件中的动态样式。 More information available at Dynamic classes and styles .更多信息可在动态类和 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);
This can be done in 3 simple steps.这可以通过 3 个简单的步骤完成。
static get properties(){
return{
newClass: String
}
}
<div class="nav-link ${this.newClass}">
<button id="hamb-btn" @click=${e=>this.newClass =”newClassName”}>☰</button>
Since this.newClass is added to properties of the element, it will rerender the DOM and update the div with class=”nav-link newClassName”由于 this.newClass 被添加到元素的属性中,它将重新渲染 DOM 并使用 class=”nav-link newClassName” 更新 div
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.