代码之家  ›  专栏  ›  技术社区  ›  Bilal Saeed

componenetDidMount()中定义的变量不可用

  •  1
  • Bilal Saeed  · 技术社区  · 7 年前

    我已经为中的两个变量设置了值 componentDidMount() . 然而,这些全局变量在我的其他函数中显示为未定义。

    componentDidMount() {
        this.authorInfo = document.getElementById("authorInfo");
        this.bottomDistance = this.authorInfo.offsetTop;
        console.log(this.authorInfo);
        document.addEventListener("scroll", this.scrollListener, false);
      }
    scrollListener() {
          console.log(this.bottomDistance);
          if (window.pageYOffset >= this.bottomDistance) {
            this.authorInfo.classList.add("sticky")
          } else {
            this.authorInfo.classList.remove("sticky");
          }
        }
    
    render() {
      return(
       .....
       <div id="authorInfo">
                  <Heading articleName="About The Author" titleFont="large"/>
                  <div className={style.profileInfo}>
                    <div style={{marginRight: '30px'}}>
                      <Image src="../../resources/images/profile.jpg" mode="fill" style={{height:'90px', width:'90px',borderRadius: '50%', display: 'inline-block'}} />
                    </div>
                    <span className={style.infoPanelText}>Proin gravida nibh vel velit auctor aliquet. Aenean sollicitudin quis bibendum auctor, nisi elit consequat ipsum, nec sagittis sem nibh id elit. Duis sed odio sit amet nibh vulputate cursus a sit amet mauris.</span>
                  </div>
                </div>
      )
    }
    

    二者都 authorInfo 底部距离 在我的scrollListeners中显示为未定义。 PS:我试过了 裁判 属性来分配全局变量的值。

    2 回复  |  直到 7 年前
        1
  •  0
  •   Sidney    7 年前

    您需要使用 .bind() 告诉JavaScript要使用什么“上下文”:

    componentDidMount() {
      this.authorInfo = document.getElementById("authorInfo");
      this.bottomDistance = this.authorInfo.offsetTop;
      console.log(this.authorInfo);
      // Notice .bind here -->                                vvvv
      document.addEventListener("scroll", this.scrollListener.bind(this), false);
    }
    scrollListener() {
      console.log(this.bottomDistance);
      if (window.pageYOffset >= this.bottomDistance) {
        this.authorInfo.classList.add("sticky")
      } else {
        this.authorInfo.classList.remove("sticky");
      }
    }
    

    当您通过 scrollListener 函数没有绑定或调用它,函数将丢失其上下文,因此 this 在未绑定版本中,指的是 window .

    有关的详细信息 .绑定() : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

        2
  •  0
  •   Nikita Borisovskiy    7 年前

    你可以通过 this 方法声明中使用箭头函数的上下文 scrollListener = () => { /* ... */ } 无需在构造函数中手动绑定。