Because in Teacher Yuan’s video, only vue is used to achieve the smooth rising effect of elements. The vue version can register instructions through Vue.directive(), and then directly bind v-slide-in to the label for easy use.
At the same time, I was thinking about whether the react version has the same operation, but I was disappointed that I couldn't find any tutorials on the react registration instructions. So just write one in your own way.
Principle: In fact, it is to operate the demo. We can get the current node through ref and then pass it to this method to make a call.
First create a vSlideIn.js file (same as the video code)
//动画运动距离
const DISTANCE = 300;
//动画时间
const DURATION = 1000;
//动画对象
const animationMap = new WeakMap()
//监听重叠
const ob = new IntersectionObserver(entries=>{
for(const entry of entries){
if(entry.isIntersecting){
console.log(entry.target)
const animation = animationMap.get(entry.target)
//播放
animation.play();
//取消监听
ob.unobserve(entry.target)
}
}
})
function isBelowViewport(el){
const rect = el.getBoundingClientRect()
return rect.top > window.innerHeight
}
export default {
mounted(el) {
if(!isBelowViewport(el)){
return
}
const animation = el.animate([
{
transform:`translateY(${DISTANCE}px)`,
opacity:0.5
},
{
transform:`translateY(0)`,
opacity:1
}
],{
duration:DURATION,
easing:'ease'
});
animation.pause()
animationMap.set(el,animation)
ob.observe(el)
},
//卸载
unmounted(el:any) {
ob.unobserve(el)
},
};
my jsx code
import { useEffect, useRef, useState } from "react";
//css自己加
import styled from "./HomePage.module.scss";
//注意自己的文件路径
import vslidein from "@/utils/vSlideIn";
const vslideins = vslidein.mounted;
//主文件
function HomePage() {
const refs1 = useRef(null);
const refs2 = useRef(null);
const refs3 = useRef(null);
const refs4 = useRef(null);
useEffect(() => {
//异步一下
setTimeout(() => {
//直接传refs1没用的会报错误,refs1.current才能拿到真正的demo
//这块和定义都可以用循环实现,没必要写这么多代码,你们自己改良即可
vslideins(refs1.current);
vslideins(refs2.current);
vslideins(refs3.current);
vslideins(refs4.current);
});
}, [refs1,refs2,refs3,refs4]);
return (
<>
<div className={styled.subject}>
<div ref={refs1} className={styled.colorA}>
1
</div>
<div ref={refs2} className={styled.colorB}>
2
</div>
<div ref={refs3} className={styled.colorC}>
3
</div>
<div ref={refs4} className={styled.colorD}>
4
</div>
</div>
</>
);
}
export default HomePage;
Forget it, I will feed the food directly into your mouth, css
.subject {
div{
width: 100vw;
height: 100vh;
}
.colorA{
background:#1c1e53;
}
.colorB{
background:#fcd980;
}
.colorC{
background:#f4f6fc;
}
.colorD{
background:#fde6b2;
}
}
Summary: Simply implement it, you can optimize and modify it yourself. In fact, it is to operate the demo, just pass the demo in