React onScroll not working

前端 未结 1 1117
别那么骄傲
别那么骄傲 2020-12-17 19:25

I\'m trying to add onscroll event handler to specific dom element. Look at this code:

class ScrollingApp extends React.Component {
    ...
    _handleScroll(         


        
相关标签:
1条回答
  • 2020-12-17 20:00

    The root of the problem is that this.refs.list is a React component, not a DOM node. To get the DOM element, which has the addEventListener() method, you need to call ReactDOM.findDOMNode():

    class ScrollingApp extends React.Component {
    
        _handleScroll(ev) {
            console.log("Scrolling!");
        }
        componentDidMount() {
            const list = ReactDOM.findDOMNode(this.refs.list)
            list.addEventListener('scroll', this._handleScroll);
        }
        componentWillUnmount() {
            const list = ReactDOM.findDOMNode(this.refs.list)
            list.removeEventListener('scroll', this._handleScroll);
        }
        /* .... */
    }
    
    0 讨论(0)
提交回复
热议问题