动画
编辑页面
了解如何集成 React Native 动画并在你的 Expo 项目中使用它。
For the complete documentation index, see llms.txt. Use this Use this file to discover all available pages.
动画是增强并提供更佳用户体验的绝佳方式。在你的 Expo 项目中,你可以使用 React Native 的 Animated API。不过,如果你想使用性能更好、更高级的动画,可以使用 react-native-reanimated 库。它提供了一个 API,简化了创建平滑、强大且易于维护的动画的过程。
安装
如果你是使用默认模板创建的项目,则可以跳过安装 react-native-reanimated。该库已经预装。否则,请运行以下命令进行安装:
Terminal
- npx expo install react-native-reanimated使用
最小示例
以下示例展示了如何使用 react-native-reanimated 库创建一个简单动画。有关该 API 和高级用法的更多信息,请参阅 react-native-reanimated 文档。
使用 react-native-reanimated
import Animated, { useSharedValue, withTiming, useAnimatedStyle, Easing, } from 'react-native-reanimated'; import { View, Button, StyleSheet } from 'react-native'; export default function AnimatedStyleUpdateExample() { const randomWidth = useSharedValue(10); const config = { duration: 500, easing: Easing.bezier(0.5, 0.01, 0, 1), }; const style = useAnimatedStyle(() => { return { width: withTiming(randomWidth.value, config), }; }); return ( <View style={styles.container}> <Animated.View style={[styles.box, style]} /> <Button title="切换" onPress={() => { randomWidth.value = Math.random() * 350; }} /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', justifyContent: 'center', }, box: { width: 100, height: 80, backgroundColor: 'black', margin: 30, }, });
其他动画库
你可以在 Expo 项目中使用其他动画包,例如 Moti。它可在 Android、iOS 和 web 上运行。