【发布时间】:2021-09-02 15:10:23
【问题描述】:
我是 React 的新手,当我的元素进入视口时,我尝试启动 CSS @keyframes 动画。
为此,我将 Intersection Observer 与 useOnScreen 挂钩:https://usehooks.com/useOnScreen/
我的 JSX:
import React, {useEffect, useRef, useState} from 'react'
import './landing.scss'
function useOnScreen(options){
const ref = React.useRef();
const [visible, setVisible] = React.useState(false);
React.useEffect(() => {
const observer = new IntersectionObserver(([entry]) => {
setVisible(entry.isIntersecting);
}, options);
if (ref.current) {
observer.observe(ref.current);
}
return () => {
if (ref.current) {
observer.unobserve(ref.current);
}
}
}, [ref, options])
return [ref, visible];
}
const Landing = () => {
const [ref, visible] = useOnScreen();
return(
<>
<div className="titleBox">
<h2 style={{ animationDuration: `0.5s`, animationIterationCount: 1, animationName: visible ? "showTopText" : ``, animationDelay: "0.3s", animationTimingFunction: "ease" }}>My text</h2>
</div>
</>
)
}
我的scss:
@keyframes showTopText {
0% {top: 100%;}
100% {top: 0;}
}
.titleBox{
width: 100%;
height: 64px;
overflow: hidden;
position: relative;
h2{
font-size: 56px;
line-height: 64px;
width: 100%;
font-weight: normal;
position: absolute;
}
}
我的主要问题是每次元素返回屏幕时动画都会重复,并且我的文本加载到 top: 0%; 并在动画开始时消失到 top: 100%;。
我该如何解决这个问题?
【问题讨论】: