如何在React Native中停止循环动画?

Mic*_*eng 9 javascript animation react-native

我在我的组件中有一个简单的循环动画,如下所示:

runAnimation() {
    console.log('run animation');
    this.state.angle.setValue(0);
    Animated.timing(this.state.angle, {
        toValue: 360,
        duration: 8000,
        easing: Easing.linear
    }).start(() => this.runAnimation());
}

...

<Animated.Image
    style={[
        styles.rotate,
        { transform: [
            { rotate: this.state.angle.interpolate({
                inputRange: [0, 360],
                outputRange: ['0deg', '360deg']
            })},
        ]}
    ]}
    source={require('./spinning_ball.png')}
/>
Run Code Online (Sandbox Code Playgroud)

我该怎么做这个动画?例如,导航到另一个屏幕或用户点击按钮后.

我尝试使用this.state.angle.stopAnimation()但注意到仍在控制台中打印运行动画.我应该调用一个不同的停止方法来阻止启动回调被执行吗?

max*_*23_ 16

基于我在NguyênHoàng的回答中的评论.如果您调用以下是另一种停止循环动画的方法this.state.angle.stopAnimation():

runAnimation() {
  this.state.angle.setValue(0);
  Animated.timing(this.state.angle, {
    toValue: 360,
    duration: 8000,
    easing: Easing.linear
  }).start((o) => {
    if(o.finished) {
      this.runAnimation();
    }
  });
}
Run Code Online (Sandbox Code Playgroud)


ima*_*gio 9

我喜欢将我的动画封装在钩子中,它比类组件更清晰、更容易、更可重用。这是我在打字稿中使用简单的开始/停止控制来制作循环动画的方法:

export const useBounceRotateAnimation = (running: boolean = true, rate: number = 300) => {
    //Example of making an infinite looping animation and controlling it with a boolean
    //Note that this assumes the "rate" is constant -- if you wanted to change the rate value after creation the implementation would have to change a bit

    //Only create the animated value once
    const val = useRef(new Animated.Value(0))

    //Store a reference to the animation since we're starting-stopping an infinite loop instead of starting new animations and we aren't changing any animation values after creation. We only want to create the animation object once.
    const anim = useRef(
        Animated.loop(
            Animated.timing(val.current, {
                toValue: 1,
                duration: rate,
                easing: Easing.linear,
                useNativeDriver: true,
                isInteraction: false,
            })
        )
    ).current

    //Interpolate the value(s) to whatever is appropriate for your case
    const interpolatedY = val.current.interpolate({
        inputRange: [0, 0.5, 1],
        outputRange: [0, 6, 0],
    })
    const interpolatedRotate = val.current.interpolate({
        inputRange: [0, 0.25, 0.5, 1],
        outputRange: ["0deg", "-3deg", "3deg", "0deg"],
    })

    //Start and stop the animation based on the value of the boolean prop
    useEffect(() => {
        if (running) {
            anim.start()
        } else {
            //When stopping reset the value to 0 so animated item doesn't stop in a random position
            anim.stop()
            val.current.setValue(0)
        }

        //Return a function from useEffect to stop the animation on unmount
        return () => anim.stop()
     //This useEffect should rerun if "running" or "anim" changes (but anim won't change since its a ref we never modify)
    }, [running, anim])

     //Return the animated values. Use "as const" const assertion to narrow the output type to exactly the two values being returned. 
    return [interpolatedY, interpolatedRotate] as const
}
Run Code Online (Sandbox Code Playgroud)

我使用这个实际的钩子实现在我的游戏中制作一个角色图像“行走”。现在在我的组件中它很容易使用:

const MyComponent = () => {
    const [isRunning, setIsRunning] = useState(true)

    const [translation, rotation] = useBounceRotateAnimation(isRunning)

    return (
        <Animated.View
            style={{
                transform: [{ translateY: translation}, { rotate: rotation}],
            }}
        >
             ....rest of your component here, just setIsRunning(false) to stop animation whenever you need
        </Animated.View>
    )
}
Run Code Online (Sandbox Code Playgroud)

如您所见,此模式非常干净且可重复使用。动画组件不需要了解有关动画的任何信息,它只使用动画值并告诉动画何时运行。


Ngu*_*àng 5

您可以创建一个变量,stopAnimation以便在您需要时通过stopAnimation === false回调runAnimation函数停止动画。比如例子:

this.state = { stopAnimation: false }

runAnimation() {
  this.state.spinValue.setValue(0);
  Animated.timing(
    this.state.spinValue,
    {
      toValue: 1,
      duration: 3000,
      easing: Easing.linear
    }
  ).start( () => {
    if(this.state.stopAnimation === false) {
      this.runAnimation();
    }
  });
}
Run Code Online (Sandbox Code Playgroud)

所以你只需要创建一个按钮来调用函数this.state = { stopAnimation: true }来停止动画。

示例如下: https: //rnplay.org/apps/Lpmh8A