【问题标题】:React trigger effect on scroll position对滚动位置做出反应触发效果
【发布时间】:2021-02-06 11:52:31
【问题描述】:

在某个组件进入视口后,我必须在它上实现一些自定义动画,在桌面模式下它应该被触发

window.scrollY > 1200

它适用于桌面但不适用于移动模式,问题是在移动模式下我的 window.scrollY 永远不会达到 1200。

我应该如何管理这样的滚动效果的响应性?

export default function Layout() {


    const [navColor, setNavColor] = useState(null);
    const [x, setX] = useState(null);

    const pop = () => {
        console.log(window.scrollY);
        if(window.scrollY > 1200){
            setX(classes.Swipe);
        }
       

        if(window.scrollY > 927) {
            setNavColor('red');
        }
        else{
            setNavColor(null);
        }
    }

    window.addEventListener('scroll', () => pop());

    return (
        <div className={classes.Layout}>
            
            <Video/>
            <Navbar color={navColor}/>
            <Picture />
            <AboutMe />
            <div className={classes.c}>tessdfsdfsfdst div</div>
            <div className={[ x,classes.Div].join(' ')}>

            </div>
        </div>
    );
}

【问题讨论】:

标签: reactjs animation scroll viewport


【解决方案1】:

首先在组件挂载时添加你的事件,在卸载时移除它(为了安全和性能):

useEffect(() => {
  window.addEventListener('scroll', pop);

  return () => window.removeEventListener('scroll', pop);
},[]);

那么你的功能可能是:

const pop = () => {
  if (window.scrollY > 1200) {
    setX(classes.Swipe);
  }
           
  if (window.scrollY > 927) {
    setNavColor('red');
  }
      
  setNavColor(null);
}

   

然后检测是否是移动的,你可以这样做:

function isMobile() {
  return window.innerWidth <= 800;
}

【讨论】:

  • 为什么 eslint 会警告我这个? “React Hook useEffect 缺少依赖项:'pop'。要么包含它,要么删除依赖数组 react-hooks/exhaustive-deps”
猜你喜欢
  • 1970-01-01
  • 2021-02-18
  • 1970-01-01
  • 2017-04-17
  • 2019-05-27
  • 1970-01-01
  • 2022-11-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多