简体   繁体   English

反应本机动画停止不起作用

[英]React native Animated stop is not working

I am trying to use React Native Animated to do simple animation with View width and Height.我正在尝试使用 React Native Animated 来使用视图宽度和高度来执行简单的 animation。 Following the official syntax from here React Animated .遵循此处React Animated的官方语法。 But the stop functionality is not working.但是停止功能不起作用。

Here is my code snippet:这是我的代码片段:

import React, { useRef } from "react";
import { Animated, View, StyleSheet, Button } from "react-native";

const App = () => {
 const sizeAnimBase = new Animated.Value(100);
 const sizeAnim = useRef(sizeAnimBase).current;
 
 const startAnimation = () => {
  Animated.timing(sizeAnim, {
      toValue: 500,
      duration: 100,
      useNativeDriver: false
    }).start(() => {
      
    });
 }

 const stopAnimation = () => {
  // Tried both ways but didn't work
  Animated.timing(sizeAnimBase).stop();
  Animated.timing(sizeAnim).stop();
 }

return (
 <View>
   <Animated.View
        style={
            width: sizeAnim, 
           height: sizeAnim
          }
      >
        <Text>Animated view</Text>
      </Animated.View>
    <Button title="Start Animation" onPress={startAnimation} />
        <Button title="Stop Animation" onPress={stopAnimation} />
 </View>
)
}

This worked for me normally这通常对我有用

const App = () => {
 const sizeAnim = useRef(new Animated.Value(100)).current;

  const startAnimation = () => {
    Animated.timing(sizeAnim, {
      toValue: 500,
      duration: 2000,
      useNativeDriver: false,
    }).start();
  };

  const stopAnimation = () => {
    Animated.timing(sizeAnim, {
      duration: 0,
      toValue: 0,
      useNativeDriver: true,
    }).stop();
  };

  return (
    <View>
      <Animated.View style={{width: sizeAnim, height: sizeAnim}}>
        <Text>Animated view</Text>
      </Animated.View>
      <Button title="Start Animation" onPress={startAnimation} />
      <Button title="Stop Animation" onPress={stopAnimation} />
    </View>
  );
}

How are you testing whether it's working or not?您如何测试它是否有效? You've set duration to 100ms, its practically impossible to press Stop Animation button before the animation completes.您已将持续时间设置为 100 毫秒,在 animation 完成之前几乎不可能按下 Stop Animation 按钮。

Increase the duration to something like 5000ms and you'll set it's working perfectly.将持续时间增加到 5000 毫秒左右,您将设置它完美运行。

Here is a snack link.是一个小吃链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM