【发布时间】:2021-03-31 08:18:49
【问题描述】:
我有一个反应页面,其主要部分在视口中的可见性由交叉点观察者观察。一旦用户看到该部分,就会触发一个关键帧(通常是从 0 到 1 的基本不透明度过渡)。
问题是每次我向上/向下滚动时关键帧都会重新开始,这从用户体验的角度来看很烦人。如何防止关键帧动画发生后再次触发?
这是一个代码sn-p:
import { useInView } from "react-intersection-observer";
const reveal = keyframes`
0% {opacity: 0;}
100% {opacity: 1;}
`;
const Section = styled.section`
margin: 64px 0;
`;
const SectionTitle = styled.h3<{ inView: boolean }>`
opacity: 0;
animation: ${({ inView }) =>
inView &&
css`
${reveal} 1s ease forwards
`};
`;
const Text = styled.p<{ inView: boolean }>`
opacity: 0;
animation: ${({ inView }) =>
inView &&
css`
${reveal} 1.5s ease forwards
`};
`;
export default function Home() {
const [about, aboutInView] = useInView();
const [pricing, pricingInView] = useInView();
return (
<div>
<Header />
<Section ref={about}>
<SectionTitle inView={aboutInView}>About</SectionTitle>
<Text inView={aboutInView}>about text</Text>
</Section>
<Section ref={pricing}>
<Text inView={pricingInView}>pricing text</Text>
</Section>
</div>
);
}
【问题讨论】:
-
因为
useInView()调用来回设置inView,你只需要确保一旦它变成true,就不会再次触发。您可以使用选项更新钩子以仅触发一次,或使用useRef和useMemo的组合仅在其为真时更改 -
谢谢,我没有看到 triggerOnce 选项 ;)!
标签: css reactjs css-animations