onScroll React cannot trigger

元气小坏坏 提交于 2021-02-08 04:38:31

问题


why if i using onScroll react version 16 cannot fire how to make it work. because i want using onScroll than onWheel?.

import ReactDom from 'react-dom'

constructor(props) {
    super(props);
    this._fireOnScroll = this.fireOnScroll.bind(this);
}

fireOnScroll() {
    console.log('Fire!');
}

componentDidMount() {
    const elem = ReactDOM.findDOMNode(this.refs.elementToFire);
    elem.addEventListener('scroll', this._fireOnScroll, true);
}

componentWillUnmount() {
    const elem = ReactDOM.findDOMNode(this.refs.elementToFire);
    elem.removeEventListener('scroll', this._fireOnScroll);
}

render() {
    return (
        <div ref="elementToFire">
      <AnotherComponent imagesUrl={Array(100)}}>}
    </div>
</div>
    );
}

回答1:


Your div is empty. scroll only fires if actual scrolling did happen.
So, your div needs to be smaller than its content and needs to show scrollbars.

See this pen for a working example.

However, there is no reason for using a ref. Simply use onScroll:

<div style={{height: 75, width: 100, overflow:'scroll'}} onScroll={this.fireOnScroll}>

See this pen for a working example.




回答2:


Your ref is not properly assigned to the div it should be <div ref = {this.elementToFire} > If not works then try

const elem = ReactDOM.findDOMNode(this.refs.elementToFire.current); Also from the code you have given O guess you missed to create a ref object also

this.elementToFire = React.createRef();

Hope it will work



来源:https://stackoverflow.com/questions/49975863/onscroll-react-cannot-trigger

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!