安装
安装依赖包
yarn add react-native-reanimated
yarn add react-native-worklets
配置
文件 babel.config.js 中添加配置:
module.exports = {
presets: [
...
],
plugins: [
...
'react-native-worklets/plugin', // Reanimated 所需配置
],
};
iOS 需要安装依赖
cd ios && pod install && cd ..
简单例子
实现效果:点击按钮后改变 View 的大小
import { View, SafeAreaView, Button } from 'react-native';
import Animated, { useAnimatedStyle, useSharedValue, withSpring } from 'react-native-reanimated';
export function ReanimatedDemoPage() {
// 定义共享值变量:影响动画变化的值
const size = useSharedValue(100);
// 定义动画改变的样式
const boxAnimatedStyles = useAnimatedStyle(() => ({
// 设置动画如何变化:withSpring 弹性、线性
width: withSpring(size.value),
height: withSpring(size.value),
}));
return (
<SafeAreaView>
<Text>动画</Text>
// 定义动画 View
<Animated.View style={[{ backgroundColor: '#0ff' }, boxAnimatedStyles]}>
</Animated.View>
<Button
onPress={() => {
// 赋值大小为随机数
size.value = Math.random() * 300;
}}
title='改变 View 大小'
/>
<SafeAreaView>
);
}