我正在使用 Typescript react 构建一个 Web 应用程序。我正在尝试制作一个在点击时展开的手风琴菜单,但它只响应第二次点击。我认为这是因为它只在第一次点击后才开始收听。
有没有办法让它从一开始就听?我尝试在构造函数中初始化事件侦听器,但它似乎不起作用。
这是我的课:
class SelectionMenu extends React.Component {
constructor(props: Readonly<{}>){
super(props);
this.listenForAccordion = this.listenForAccordion.bind(this);
}
// opens and closes the accordian menu
public listenForAccordion(): void {
for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function() {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.maxHeight){
panel.style.maxHeight = null;
} else {
panel.style.maxHeight = panel.scrollHeight + "px";
}
});
}
}
public render() {
return (
<div className="App-selectionmenu">
<button className="Accordion" onClick={this.listenForAccordion}>Section 1</button>
<div className="Panel">
<p>Lorem ipsum...</p>
</div>
<button className="Accordion" onClick={this.listenForAccordion}>Section 2</button>
<div className="Panel">
<p>Lorem ipsum...</p>
</div>
<button className="Accordion" onClick={this.listenForAccordion}>Section 3</button>
<div className="Panel">
<p>Lorem ipsum...</p>
</div>
</div>
);
}
}