react native实现动画
使用 Animated API 实现基础动画
React Native 提供了 Animated API 用于创建流畅的动画效果。通过定义动画值(Animated.Value)和控制动画方法(如 timing、spring)实现。
import React, { useRef, useEffect } from 'react';
import { Animated, View, StyleSheet } from 'react-native';
const FadeInView = () => {
const fadeAnim = useRef(new Animated.Value(0)).current;
useEffect(() => {
Animated.timing(fadeAnim, {
toValue: 1,
duration: 2000,
useNativeDriver: true,
}).start();
}, [fadeAnim]);
return (
<Animated.View style={{...styles.box, opacity: fadeAnim}} />
);
};
const styles = StyleSheet.create({
box: {
width: 100,
height: 100,
backgroundColor: 'blue',
}
});
组合动画效果
通过 Animated.parallel 或 Animated.sequence 组合多个动画,实现复杂效果。

const combinedAnim = () => {
const scaleAnim = useRef(new Animated.Value(1)).current;
const rotateAnim = useRef(new Animated.Value(0)).current;
useEffect(() => {
Animated.parallel([
Animated.spring(scaleAnim, {
toValue: 1.5,
friction: 2,
useNativeDriver: true,
}),
Animated.timing(rotateAnim, {
toValue: 1,
duration: 1000,
useNativeDriver: true,
})
]).start();
}, []);
const rotateInterpolate = rotateAnim.interpolate({
inputRange: [0, 1],
outputRange: ['0deg', '360deg']
});
return (
<Animated.View style={{
transform: [
{ scale: scaleAnim },
{ rotate: rotateInterpolate }
]
}} />
);
};
使用 LayoutAnimation 实现布局动画
LayoutAnimation 适用于组件布局变化时的自动过渡动画,如列表项增删。

import { LayoutAnimation, UIManager, Platform } from 'react-native';
if (Platform.OS === 'android') {
UIManager.setLayoutAnimationEnabledExperimental(true);
}
const toggleAnimation = () => {
LayoutAnimation.configureNext(
LayoutAnimation.Presets.spring
);
// 触发状态变化导致布局更新
};
手势驱动的动画
通过 PanResponder 结合 Animated 实现拖拽等交互式动画。
const panResponder = PanResponder.create({
onMoveShouldSetPanResponder: () => true,
onPanResponderMove: Animated.event(
[null, { dx: pan.x, dy: pan.y }],
{ useNativeDriver: false }
),
onPanResponderRelease: () => {
Animated.spring(pan, {
toValue: { x: 0, y: 0 },
useNativeDriver: true
}).start();
}
});
return (
<Animated.View
{...panResponder.panHandlers}
style={{ transform: pan.getTranslateTransform() }}
/>
);
使用 Reanimated 2 库实现高性能动画
当需要复杂手势或60FPS动画时,推荐使用 react-native-reanimated 库。
import Animated, {
useSharedValue,
withSpring,
useAnimatedStyle,
} from 'react-native-reanimated';
const ReanimatedExample = () => {
const offset = useSharedValue(0);
const animatedStyles = useAnimatedStyle(() => ({
transform: [{ translateX: offset.value * 255 }],
}));
return (
<>
<Animated.View style={[styles.box, animatedStyles]} />
<Button
title="Move"
onPress={() => offset.value = withSpring(Math.random())}
/>
</>
);
};
注意事项
- 始终添加
useNativeDriver: true提升性能(部分动画不支持) - 避免在
useNativeDriver启用时使用非变换样式(如 width/height) - 复杂动画建议使用
react-native-reanimated替代原生Animated - 使用
InteractionManager处理动画与复杂任务的调度






