![](/img/trans.png)
[英]component snapping effect when animation transitions out in react-spring?
[英]Start animation in react-spring when component is in view
我正在使用react-spring
制作动画,一旦页面加载,所有动画就会开始。 我想控制动画的开始。 期望的结果是让屏幕中的组件在视图中(即用户向下滚动)后开始动画。 代码如下:
const cols = [
/*Components here that will be animated ..*/
{component: <div><p>A<p></div> , key:1},
{component: <div><p>B<p></div> , key:2},
{component: <div><p>C<p></div> , key:3},
]
export default function foocomponent(){
const [items, setItems] = React.useState(cols);
const [appear, setAppear] = React.useState(false); // Should trigger when the component is in view
const transitions = useTransition(items, (item) => item.key, {
from: { opacity: 0, transform: 'translateY(70px) scale(0.5)', borderRadius: '0px' },
enter: { opacity: 1, transform: 'translateY(0px) scale(1)', borderRadius: '20px', border: '1px solid #00b8d8' },
// leave: { opacity: 1, },
delay: 200,
config: config.molasses,
})
React.useEffect(() => {
if (items.length === 0) {
setTimeout(() => {
setItems(cols)
}, 2000)
}
}, [cols]);
return (
<Container>
<Row>
{appear && transitions.map(({ item, props, key }) => (
<Col className="feature-item">
<animated.div key={key} style={props} >
{item.component}
</animated.div>
</Col>
))}
</Row>
</Container>
);
}
我尝试使用appear && transitions.map(...)
但不幸的是这不起作用。 知道我应该如何根据条件控制动画的开始吗?
我使用https://github.com/civiccc/react-waypoint解决此类问题。
如果您将这个隐藏组件放在动画之前。 你可以用它来切换出现状态。 像这样的东西:
<Waypoint
onEnter={() => setAppear(true) }
/>
你甚至可以用它指定一个偏移量。 微调体验。
如果您希望各个部分淡入、滚动,无论输入什么,创建自定义包装器实际上非常简单。 由于这个问题与 React Spring 相关,这里有一个示例,但您也可以稍微重构一下以使用纯 CSS。
// React
import { useState } from "react";
// Libs
import { Waypoint } from "react-waypoint";
import { useSpring, animated } from "react-spring";
const FadeIn = ({ children }) => {
const [inView, setInview] = useState(false);
const transition = useSpring({
delay: 500,
to: {
y: !inView ? 24 : 0,
opacity: !inView ? 0 : 1,
},
});
return (
<Waypoint onEnter={() => setInview(true)}>
<animated.div style={transition}>
{children}
</animated.div>
</Waypoint>
);
};
export default FadeIn;
然后,您可以将要在视图中淡入的任何组件包装在此 FadeIn 组件中,如下所示:
<FadeIn>
<Clients />
</FadeIn>
或者写你自己的html:
<FadeIn>
<div>
<h1>I will fade in on enter</h1>
</div>
</FadeIn>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.