reactjs - 如何在同一个反应组件中使用多个“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;
解决方案
在他们的文档中,它说您可以将多个变量与数组破坏一起使用,而不是在您自己的案例中使用的对象破坏。
所以你应该这样做。
const [ref, inView ] = useInView()
const [ref2, inView2 ] = useInView()
推荐阅读
- node.js - 节点 api 路由不返回任何状态码
- python - 为什么 `lambda: MyClass()` 是合法的,但 `MyClass()` 本身是非法的?
- java - java.util.Timer 中 timer.schedule() 队列的池大小是多少
- javascript - Javascript编程方式获取两个日期对象之间30分钟间隔的时间
- typescript - 插值字符串类型不能用于索引与键类型相同的记录
- google-sheets - Google 表格 - 将数据透视表过滤到最近的日期
- java - 为什么 Pojo2Json 转换器(使用杰克逊)循环
- security - Ansible:有条件地处理插件并将变量或寄存器传递给它们
- json - 将 zeek 连接数据加载到 pyflink
- javascript - 溢出-y:滚动或自动不按预期工作。它没有滚动