【问题标题】:javascript addEventListener in react js component not workingreact js组件中的javascript addEventListener不起作用
【发布时间】:2020-04-23 03:10:49
【问题描述】:

第一次运行程序运行正常。 但点击加号或减号按钮后,该功能将无法运行。

componentDidMount() {

if(CONST.INTRO) {

    this.showIntro(); // show popup with next and prev btn

    let plus = document.querySelector('.introStep-plus');
    let minus = document.querySelector('.introStep-minus');

    if (plus || minus) {

        plus.addEventListener('click',  () => {
            let next = document.querySelector(CONST.INTRO[this.state.introStep].element);
            if (next) {
                next.parentNode.removeChild(next);
            }

            this.setState({
                introStep: this.state.introStep + 1
            });

            this.showIntro();


        });
    }
}

【问题讨论】:

    标签: javascript reactjs dom-manipulation


    【解决方案1】:

    正如 React 文档中所引用的:refs and the dom 引用 DOM 元素的正确方法是使用 react.creatRef() 方法,即使这样,文档也建议不要过度使用它:

    避免将 refs 用于任何可以以声明方式完成的事情。

    我建议你在你的 react 组件渲染方法中管理你的 .introStep-plusintroStep-minus DOM 元素,使用条件渲染,并保持显示和隐藏 .introStep-plus DOM 元素的状态,而不是在本机 javascript @ 中删除它987654325@点击

    这是一个建议的修改,它可能不会直接起作用,因为您没有提供更多上下文以及您是如何实现整个组件的。

    constructor() {
      ...
      this.state = {
        ...
        showNext: 1,
        ...
      }
      ...
    
      this.handlePlusClick = this.handlePlusClick.bind(this);
    }
    
    componentDidMount() {
      if(CONST.INTRO) {
          this.showIntro(); // show popup with next and prev btn
      }
    }
    
    handlePlusClick(e) {
      this.setState({
          introStep: this.state.introStep + 1,
          showNext: 0,
      });
      this.showIntro();
    });
    
    render() {
      ...
      <div className="introStep-plus" onClick={this.handlePlusClick}></div>
      <div className="introStep-minus"></div>
      {(this.stat.showNext) ? (<div> NEXT </div>) : <React.fragment />}
      ...
    }
    

    【讨论】:

      猜你喜欢
      • 2021-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-27
      • 2011-06-20
      • 1970-01-01
      • 2011-02-22
      • 1970-01-01
      相关资源
      最近更新 更多