簡體   English   中英

反應添加/刪除事件監聽器

[英]React add/remove event listener

由於某種原因, this.getVisible()不會在滾動/調整大小事件上觸發。 有人可以告訴我問題是什么嗎?

import React, { Component } from 'react'

const ZeroSum = ({
  selector,
  ...passedProps,
}) => WrappedComponent => class WithZeroSum extends Component {
  constructor(props) {
    super(props)
    this.selector = document.querySelector(selector)
    this.state = {
      zeroSum: 0,
    }
  }

  componentWillMount() {
    window.addEventListener('scroll resize', () => this.getVisible())
    this.getVisible()
  }

  componentWillUnmount() {
    window.removeEventListener('scroll resize', () => this.getVisible())
  }

  getVisible() {
    const vHeight = document.documentElement.clientHeight
    const eTop = this.selector.getBoundingClientRect().top
    return this.setState({ zeroSum: Math.max(0, vHeight - eTop) })
  }

  render() {
    const { zeroSum } = this.state
    const props = { ...this.props, ...passedProps }
    console.log(zeroSum)
    return <WrappedComponent {...props} zeroSum={zeroSum} />
  }
}

export default ZeroSum

您不能在其中傳遞多種事件類型。 嘗試這個:

constructor(props) {
    // ...
    this.state = {
        // ...
        listener: this.getVisible.bind(this)
    };
}

componentWillMount(){
    window.addEventListener("scroll", this.state.listener);
    window.addEventListener("resize", this.state.listener);
    this.state.listener();
}

componentWillUnount(){
    window.removeEventListener("scroll", this.state.listener);
    window.removeEventListener("resize", this.state.listener);
}
constructor(props) {
super(props)
this.selector = document.querySelector(selector)
this.state = {
  zeroSum: 0,
}
  this.getVisible.bind(this) // bind all your class methods to this

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM