LitElement:从属性设置样式

问题描述 投票:1回答:1

我正在使用LitElement构建自定义Web组件,并希望为其提供disabled属性。我已经完成了样式设置,但恐怕我正在使用反模式来完成它。我已经定义了一个类方法,并在render()方法中调用它来设置所需的样式。这是正确的还是有更好的模式?谢谢。

Javascript:

import {LitElement, html, css} from 'lit-element'
import {styleMap} from 'lit-html/directives/style-map'

class Button extends LitElement {
    static get properties() { return {
        disabled: {type: Boolean}
        }
    }

    constructor() {
        super();

        this.disabled = false;
        this.innerButtonText = this.innerHTML;
        this.styles = {}
    }

    render() {
        this.setStyles();
        return html`
        <style>@import "https://fonts.googleapis.com/css?family=Montserrat:700";</style>
        <button style=${styleMap(this.styles)}>${this.innerButtonText}</button>
      `
    }

    setStyles() {
        if (this.disabled)
            this.styles = {
                backgroundColor: 'rgba(51,51,51,0.22)', color: 'rgba(51,51,51,0.66)', fontFamily: 'Montserrat', fontWeight: '700', height: '45px',
                padding: '15px 30px 15px 30px', borderRadius: '5px', border: 'none', boxShadow: '0px 1px 3px #33333338', lineHeight: '1.3', letterSpacing: '1.3px'
            };
        else{
            this.styles = {
                backgroundColor: '#2e7d32', color: 'white', fontFamily: 'Montserrat', fontWeight: '700', height: '45px',
                padding: '15px 30px 15px 30px', borderRadius: '5px', border: 'none', boxShadow: '0px 1px 3px #33333338', lineHeight: '1.3', letterSpacing: '1.3px'
            };
        }
    }
}

customElements.define('custom-button', Button);

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<style>@import "https://fonts.googleapis.com/css?family=Montserrat:700";</style>
<script type="module" src="./components/button/button.js"></script>
<body>
<custom-button>Button</grange-button>
<button>Button</button>
</body>
</html>
javascript polymer web-component lit-element
1个回答
3
投票

首先,将reflect option添加到reflect属性,以便该属性“反映”该属性的值:

disabled

接下来,创建一个static get properties() { return { disabled: { type: Boolean, reflect: true, }, }; } 来定义styles static getter在其默认和禁用状态下的样式:

styles

最后,在<button>方法中设置import { LitElement, css, html } from 'lit-element'; // ... static get styles() { return css` button { background-color: #2e7d32; color: white; /* ... */ } button[disabled] { background-color: rgba(51,51,51,0.22); color: rgba(51,51,51,0.66); } `; } <button>属性:

disabled

((您会注意到,我也摆脱了render属性,转而使用更惯用的render() { return html` <button ?disabled=${this.disabled}><slot></slot></button> `; } 。]

您可以在下面的代码段中看到所有这些协同工作:

innerButtonText
<slot> element
© www.soinside.com 2019 - 2024. All rights reserved.