为什么无法读取属性 'classList'?

Why the property 'classList' cannot be read?

我正在尝试根据变量是否等于 0 添加和删除 class。这是我的代码:

import { LitElement, html } from 'lit-element';

class SelectCounter extends LitElement {
static get properties() {
    return {
        numPassengers: {type: Number},
    };
}

constructor() {
    super();
    this.numPassengers = 0;
    this.disableState();
}

createRenderRoot() {
    return this;
}

disableState() {
    this.btn = document.querySelector('.minus');
    if (this.numPassengers === 0) {
        this.btn.classList.add('counter__btn--disable');
    }
}

render(){
    return html`
        <div class="counter">
            <a class="counter__btn minus" href="#"></a>
            <span class="counter__label">${this.numPassengers}</span>
            <a class="counter__btn" href="#"></a>
        </div>
    `;
}
}
customElements.define('select-counter', SelectCounter);

我试过几种方法,但我不明白为什么会这样。有什么想法吗?

你在构造函数中调用 disableState(),当组件的 DOM 还没有准备好时,所以这个:

this.btn = document.querySelector('.minus');

null.

如果您在 firstUpdated() 中移动该逻辑,那么它应该可以工作。

firstUpdated() {
    disableState();
}

disableState() {
    // Also, consider querySelecting inside this.renderRoot
    // to avoid picking elements with the same class in
    // other parts of the document
    this.btn = this.renderRoot.querySelector('.minus');
    // ...
}

请注意,您可以用更明确的方式做同样的事情,而不需要 select 元素:

render() {
    return html`
        <div class="counter">
            <a class="counter__btn minus ${this.numPassengers === 0 ? 'counter__btn--disable' : ''}" href="#"></a>
            <span class="counter__label">${this.numPassengers}</span>
            <a class="counter__btn" href="#"></a>
        </div>
    `;
}

或使用 lit-htmlclassMap 指令:

import {classMap} from 'lit-html/directives/class-map.js';

// ...

render() {
    return html`
        <div class="counter">
            <a class=${classMap({
                counter__btn: true,
                minus: true,
                'counter__btn--disable': this.numPassengers === 0,
            })} href="#"></a>
            <span class="counter__label">${this.numPassengers}</span>
            <a class="counter__btn" href="#"></a>
        </div>
    `;
}