反应本土动画,完成事件

Animated.spring 结束时触发事件的最佳实践是什么?

Animated.spring(this.state.pan, {
toValue: 0
}).start()

我找了很多地方都没有找到一种方法。我可以使用 addListener 来检查动画是否已经达到了它的最终值或超时,但是它们都感觉像是超级简单的丑陋修复程序。

有人知道吗?

44978 次浏览

Half an hour of googling later and i found this, can't believe they didn't document this better.

https://github.com/facebook/react-native/issues/3212

.start(callback)

This will get fired at the start of the animation

.start(console.log("Start Animation")

Using an arrow function or function, done will get called at the END of the animation

.start(() => {console.log("Animation DONE")})

And finaly this is what it looks like in the context to of a function.

_play(){
Animated.timing(this.state.progress, {
toValue: 1,
duration: 5000,
easing: Easing.linear,
}).start(() => {console.log("Animation DONE")});
}

Hope that helps!

Basically there these three approaches to do something when an animation finishes. First: you can use the callback passed into call(callback) method. Second: You can use stopAnimation which also accepts a callback Third: My preferred way,which consisting in placing a listener on the animated value,and do something based on the current value. For example, you can make a translation from 0 to 150 and based on a value you animate, say 'motion' and when motion reaches a value you can perform something.

let motion = Animated.Value(0);


motion.addListener(({value}) =>{
if(value>=10){
pos.stopAnimation((val)=>{console.log('stopped in '+val)});
}
});

More on👉https://www.youtube.com/channel/UCl5-W0A8tE3EucM7E_yS62A

Now there are docs for this: https://reactnative.dev/docs/animated#working-with-animations

The updated answer should be:

.start(({finished}) => {
if (finished) {
console.log('animation ended!)
}
})