React原生动画停止不起作用



我正在尝试使用React Native Animated来制作具有视图宽度和高度的简单动画。遵循这里的官方语法React Animated。但是停止功能不起作用。

这是我的代码片段:

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>
)
}

这对我正常工作

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>
);
}

如何测试它是否工作?您已经将持续时间设置为100ms,在动画完成之前几乎不可能按下"停止动画"按钮。

将持续时间增加到5000毫秒左右,你就会设置它完美工作。

这是一个小吃链接。

最新更新