要动态启动新动画,您需要一个条件。您可以使用 react-native 中的“动画”。而不是 state,设置一个 ref,并更改 ref 值。
import { Animated } from "react-native";
// this value can be animated one value to another
const animationRef = useRef<Animated.Value>(new Animated.Value(0));
if(condition){
// pass array of animations
Animated.sequence([
Animated.timing(animationRef.current, {
toValue: 1,
// set the duration
duration: 500,
useNativeDriver: false
}),
// delay is optional
Animated.delay(1000),
Animated.timing(animationRef.current, {
toValue: 0,
duration: 500,
// useNativeDriver:true, might not work with the all properties that you need to animate. true might improve animation performance
useNativeDriver: false
})
]).start();
}
现在在 jsx 中你需要设置你的组件:
// Touchable opacity cannot be animated
<TouchableOpacity style={styles.item}>
<Animated.View
style={[
styles.itemBackground,
{
backgroundColor: animationRef.current.interpolate({
inputRange: [0, 1],
// if value is 0 color:black, value is 1 color:white
outputRange: [colors.black, colors.white]
})
}
]}
/>
</TouchableOpacity>
Animated.View 位置应该是绝对的。将 CSS 的动态部分保留在组件中,但您可以将其他 CSS 保留在不同的文件中。
//styles.itemBackground:
itemBackground: { position: "absolute", top: 0, left: 0, right: 0, bottom: 0 }