Typescript:在类中初始化事件侦听器

时间:2018-11-02 20:29:45

标签: reactjs typescript react-tsx

我正在使用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>
        );
    }
}

1 个答案:

答案 0 :(得分:1)

您可以使手风琴行信息保持在组件状态,而不是手动操作DOM,然后单击并在render方法中将行设置为active并更改应用于该行的样式。

示例

class SelectionMenu extends React.Component {
  state = {
    rows: [{ active: false }, { active: false }, { active: false }]
  };

  onClick = index => {
    this.setState(previousState => {
      const rows = [...previousState.rows];
      rows[index] = { ...rows[index], active: !rows[index].active };
      return { rows };
    });
  };

  render() {
    return (
      <div className="App-selectionmenu">
        {this.state.rows.map((row, index) => (
          <div key={index}>
            <button className="Accordion" onClick={() => this.onClick(index)}>
              Section 1
            </button>
            <div className="Panel">
              <p>Lorem ipsum... {row.active && " (Active!)"}</p>
            </div>
          </div>
        ))}
      </div>
    );
  }
}

ReactDOM.render(<SelectionMenu />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>