【问题标题】:How to use multiple 'useInView' hooks in the same react component?如何在同一个反应组件中使用多个“useInView”挂钩?
【发布时间】:2020-10-12 15:30:23
【问题描述】:

我正在开发一个 react 项目,并尝试在 div 出现在视图中后对其进行动画处理和显示。我正在使用“react-intersection-observer”中的 useInView 挂钩来确定 div 是否在视图中,然后启动动画以使 div 可见。

但是,当我在同一个组件中有两个 div 时,这不起作用,即,只要第一个 div 在视图中 - 动画并显示第一个 div,并且当您进一步滚动第二个时div 在视图中 - 动画并显示第二个 div。

任何帮助将不胜感激。

代码如下:

import { motion } from 'framer-motion';
import { useInView } from 'react-intersection-observer';

function Container(props) {

    const { ref, inView } = useInView({
        threshold: 1
    });

    const { ref1, inView1 } = useInView({
        threshold: 1
    });

    return (
        <div>
            <motion.div ref={ref}>
                <motion.h1 
                   initial={{  x: -700, opacity: 0 }} 
                   animate={ inView ? { x: 0,  opacity: 1 } : ''} 
                   transition={{ duration: .75 }} >
                     Sample Title 1
                </motion.h1>
                <motion.p 
                   initial={{  x: 400, opacity: 0 }} 
                   animate={ inView ? { x: 0,  opacity: 1 } : ''} 
                   transition={{ delay: 0.8, duration: 1, ease: "easeOut" }} >
                     Sample Description 1
                </motion.p>
            </motion.div>

            <motion.div ref={ref1}>
                <motion.h1 
                   initial={{ opacity: 0 }} 
                   animate={ inView1 ? { opacity: 1 } : ''} 
                   transition={{ duration: .75 }} >
                     Sample Title 2
                </motion.h1>
                <motion.p
                   initial={{  x: 400, opacity: 0 }} 
                   animate={ inView1 ? { x: 0,  opacity: 1 } : ''} 
                   transition={{ delay: 0.8, duration: 1, ease: "easeOut" }} >
                     Sample Description 2
                </motion.p>
            </motion.div>         
        </div>
    );
}

export default Container;



【问题讨论】:

    标签: reactjs intersection-observer framer-motion


    【解决方案1】:

    在他们的文档中,它说您可以使用多个变量进行数组破坏,而不是您在自己的案例中使用的对象破坏。

    所以你应该这样做。

    const [ref, inView ] = useInView()
    const [ref2, inView2 ] = useInView()
    

    【讨论】:

      【解决方案2】:

      我猜你应该正确地将动画与交叉事件联系起来

      1. 动画控制:https://www.framer.com/api/motion/utilities/#animate
      2. InVew 来自 'react-intersection-observer' 与
      const from = useMotionValue(0);
      
      useEffect(
        () => {
          if (inView) {
            const controls = animate(x, 100, {
              type: "spring",
              stiffness: 2000,
            })
      
            return controls.stop
          }
        },
        [inView]
      }
      

      【讨论】:

        猜你喜欢
        • 2021-12-04
        • 2022-12-01
        • 2021-06-16
        • 2020-01-09
        • 2020-11-25
        • 2021-06-22
        • 2022-01-12
        • 2020-08-05
        • 2020-09-12
        相关资源
        最近更新 更多