首页 > 解决方案 > 如何在同一个反应组件中使用多个“useInView”挂钩?

问题描述

我正在做一个反应项目,并尝试在视图中设置动画并显示 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;



标签: reactjsintersection-observerframer-motion

解决方案


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

所以你应该这样做。

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

推荐阅读