React.js best practice regarding listening to window events from components

后端 未结 4 772
耶瑟儿~
耶瑟儿~ 2020-12-01 02:11

I am animating several React.js components based on their position in the viewport. If the component is in the viewport, animate the opacity to 1, if it\'s not in the viewpo

4条回答
  •  无人及你
    2020-12-01 02:33

    Here is a simpler code snippet that should work as required. You are missing the this binding, as such, when you execute window.addEventListener('scroll', this.handleScroll); you are actually pointing this to the window object.

    Instead you will need to bind this in the constructor. Hope it

    class Home extends Component {
      constructor(props) {
        super(props)
        this.handleScroll = this.handleScroll.bind(this);
      }
      componentDidMount() {
        window.addEventListener('scroll', this.handleScroll);
      }
      componentWillUnmount() {
        window.removeEventListener('scroll', this.handleScroll);
      }
      handleScroll(e) {
        console.log('scroll event');
        console.log(e);
      }
    
      render() {
        return (
         
    ); } }

    Another option is the below, both options should work :)

    class Home extends Component {
      componentDidMount() {
        window.addEventListener('scroll', this.handleScroll.bind(this));
      }
      componentWillUnmount() {
        window.removeEventListener('scroll', this.handleScroll.bind(this));
      }
      handleScroll(e) {
        console.log('scroll event');
        console.log(e);
      }
    
      render() {
        return (
         
    ); } }

提交回复
热议问题