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

后端 未结 4 766
耶瑟儿~
耶瑟儿~ 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:28

    Here it is in functional style with the useEffect hook:

      let onScroll = (event) => {
        console.log("scrolling");
      }
      useEffect(() => {
        if (window){
          window.addEventListener('scroll', onScroll);
        }
        return () => {
          window.removeEventListener('scroll', onScroll);
        }
      }, []);
    

提交回复
热议问题