我不知道我在这里错过了什么。我正在https://www.youtube.com/watch?v=g1Zd0Y7OJuI&t=723s中学习使用Web组件构建自定义日期选择器的教程,并将JavaScript逻辑转换为Typescript。我遇到了connectedCallback() {...}
中的一行,它抛出了以下错误:Type 'HTMLCollection | undefined' must have a '[Symbol.iterator]()' method that returns an iterator
on line const [prevBtn, calendarDateElement, nextBtn] = this.calendarDropdown?.querySelector(".calendar-header")?.children;
我在Stackoverflow上看过类似的问题,但发现他们建议的解决方案对我不起作用。请帮助我了解我需要考虑什么来消除这个可怕的错误!
class DatePicker extends HTMLElement {
shadow: ShadowRoot;
calendar: Calendar;
mounted: boolean = false;
/** Elements */
calendarDropdown: Element | null = null;
calendarDateElement: HTMLHeadingElement | null | undefined = null;
constructor() {
super();
...
}
connectedCallback() {
this.mounted = true;
this.toggleButton = this.shadow.querySelector(".date-toggle");
this.calendarDropdown = this.shadow.querySelector(".calendar-dropdown");
const [prevBtn, calendarDateElement, nextBtn] = this.calendarDropdown?.querySelector(".calendar-header")?.children; // <--- This is the line complain
this.calendarDateElement = calendarDateElement;
this.toggleButton?.addEventListener("click", () => this.toggleCalendar());
prevBtn.addEventListener("click", () => this.prevMonth());
nextBtn.addEventListener("click", () => this.nextMonth());
}
}
1条答案
按热度按时间gpnt7bae1#
我查找了这个资源https://www.javascripttutorial.net/javascript-dom/javascript-get-child-element/,找到了一个解决问题的方法,但我希望有一个更好的解决方案。我没有像
const [prevBtn, calendarDateElement, nextBtn] = this.calendarDropdown?.querySelector(".calendar-header")?.children;
这样重构父节点的子节点,而是找到了每个节点,并将其分别赋给一个变量,如以下代码所示:下面是整个类: