Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

reactjs - React onScroll not working

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

class ScrollingApp extends React.Component {
    ...
    _handleScroll(ev) {
        console.log("Scrolling!");
    }
    componentDidMount() {
        this.refs.list.addEventListener('scroll', this._handleScroll);
    }
    componentWillUnmount() {
        this.refs.list.removeEventListener('scroll', this._handleScroll);
    }
    render() {
        return (
            <div ref="list">
                {
                    this.props.items.map( (item) => {
                        return (<Item item={item} />);
                    })
                }
            </div>
        );
    }
}

Code is quite simple, and as you can see, I want to handle div#list scrolling. When I was running this example, it isn't working. So I tried bind this._handleScroll on render method directly, it doesn't work either.

<div ref="list" onScroll={this._handleScroll.bind(this)> ... </div>

So i opened chrome inspector, adding onscroll event directly with:

document.getElementById('#list').addEventListener('scroll', ...);

and it is working! I don't know why this happens. Is this a bug of React or something? or did I missed something? Any device will very appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
    }
    /* .... */
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...