Not getting callback after adding an event listener for scroll event in React.js

前端 未结 3 1931
说谎
说谎 2021-02-19 09:38

I followed the instruction from this post Update style of a component onScroll in React.js to register event listener for scroll event.

I have a React component that ren

相关标签:
3条回答
  • 2021-02-19 10:07

    Thank you dannyjolie - this work

    elementScrollData = (value) => {
      console.log('elementScrollData ', value);
    } 
    return (
          <div className="css-scroll-class" onScroll={elementScrollData}>
              Scroll element
          </div>
           );
    }
    
    0 讨论(0)
  • 2021-02-19 10:17

    For me the only thing that worked was adding true to the third argument in the EventListener:

    
    componentDidMount() {
      window.addEventListener('scroll', this.handleScroll, true);
    }
    
    componentWillUnmount() {
      window.removeEventListener('scroll', this.handleScroll, true);
    }
    
    

    Source: https://github.com/facebook/react/issues/5042#issuecomment-145317519

    0 讨论(0)
  • 2021-02-19 10:22

    Your code looks good, so it's probably not the window itself that is scrolling. Is the table placed inside a div or something that has overflow: auto or overflow:scroll? If so, the listener must be attached to the actual element that is scrolling, e.g.

    document.querySelector('.table-wrapper')
        .addEventListener('scroll', this.handleScroll);
    

    If this is the case, then just adding a React onScroll handler to the wrapper in your code would be better

    <div onScroll={this.handleScroll}><Table....
    
    0 讨论(0)
提交回复
热议问题