如何处理类打字稿中的事件?

时间:2019-10-11 17:06:03

标签: typescript

我需要处理一个事件并获取其parentNode。但是,我得到一个错误:'TodoList'类型上不存在'Property'parentNode'

我尝试使用this.parentNode,但仍然出现错误

class TodoList {
    constructor() {
        const checkbox: HTMLElement = 
        todoItem.querySelector('.checkbox');
        checkbox.addEventListener('change', this.toggleTodoItem);
}

    toggleTodoItem(): void {
      let node = this.parentNode;
      node.classList.toggle('completed'); 
    };
}

1 个答案:

答案 0 :(得分:0)

您的TodoList类根本不包含名为parentNode的实例属性,这就是为什么会出现错误的原因。相反,您是否要编写类似this的代码?

// todoItem is accessible from somewhere in your code
declare const todoItem: HTMLElement

class TodoList {
    private checkboxNode: HTMLElement

    constructor() {
        const maybeCheckboxNode = todoItem.querySelector<HTMLElement>('.checkbox');
        if (maybeCheckboxNode) {
            this.checkboxNode = maybeCheckboxNode
            this.checkboxNode.addEventListener('change', this.toggleTodoItem);
        } else throw new Error("Element not found.")
    }

    toggleTodoItem(): void {
        // assuming you mean the parent of checkbox node by `this.parentNode` in sample
        // cast node here, because parentNode doesn't have narrowed type
        let node = this.checkboxNode.parentNode as HTMLElement | null;
        node && node.classList.toggle('completed');
    };
}
相关问题