了解如何集成 react-native-reanimated 库并在你的 Expo 项目中使用它。
动画是增强和提供更好用户体验的好方法。在你的 Expo 项目中,你可以使用 React Native 中的 动画 API。但是,如果你想使用性能更好的更高级动画,可以使用 react-native-reanimated
库。它提供了一个 API,可以简化创建流畅、强大且可维护的动画的过程。
¥Animations are a great way to enhance and provide a better user experience. In your Expo projects, you can use the Animated API from React Native. However, if you want to use more advanced animations with better performance, you can use the react-native-reanimated
library. It provides an API that simplifies the process of creating smooth, powerful, and maintainable animations.
¥Installation
如果你使用 这篇博文 创建了项目,则可以跳过安装 react-native-reanimated
。此库已安装。否则,请通过运行以下命令进行安装:
¥You can skip installing react-native-reanimated
if you have created a project using the default template. This library is already installed. Otherwise, install it by running the following command:
-
npx expo install react-native-reanimated
¥Usage
¥Minimal example
下面的例子展示了如何使用 react-native-reanimated
库创建一个简单的动画。有关 API 和高级用法的更多信息,请参阅 react-native-reanimated
文档。
¥The following example shows how to use the react-native-reanimated
library to create a simple animation. For more information on the API and advanced usage, see react-native-reanimated
documentation.
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="toggle"
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,
},
});
¥Other animation libraries
你可以在 Expo 项目中使用其他动画包,例如 莫蒂。它适用于 Android、iOS 和 Web。
¥You can use other animation packages such as Moti in your Expo project. It works on Android, iOS, and web.