React Native Reanimated报错:undefined is not a constructor问题求助
解决React Native Reanimated 3.x的
Value构造函数未定义错误 错误原因
你使用的是React Native Reanimated 3.4.2,但代码里沿用了v2及更早版本的API(Value、旧版timing),这些API在v3中已被彻底移除,因此触发undefined is not a constructor错误。
修复步骤
1. 替换为Reanimated 3.x兼容的API
将旧版API替换为v3的新规范:
- 用
useSharedValue替代new Value()创建动画状态值 - 用
withTiming替代旧版timing实现时间动画 - 用
useAnimatedStyle生成绑定动画值的样式 - 用
runOnUI确保动画逻辑在UI线程执行
修正后的完整代码:
import React from 'react'; import { View, Text, StyleSheet, Dimensions, TouchableOpacity } from 'react-native'; import Animated, { useSharedValue, useAnimatedStyle, withTiming, Easing, runOnUI } from 'react-native-reanimated'; const { width } = Dimensions.get('window'); const AnimatedProductList = () => { const translateY = useSharedValue(0); const animationDuration = 3000; // 3秒 const startAnimation = () => { runOnUI(() => { // 向上移动10像素 translateY.value = withTiming(-10, { duration: animationDuration / 2, easing: Easing.inOut(Easing.ease), }, () => { // 动画结束后回到原位置 translateY.value = withTiming(0, { duration: animationDuration / 2, easing: Easing.inOut(Easing.ease), }); }); })(); }; // 创建绑定动画值的样式 const animatedStyle = useAnimatedStyle(() => { return { transform: [{ translateY: translateY.value }], }; }); return ( <View style={styles.container}> <View style={styles.productBox}> <Text style={styles.productName}>Product 1</Text> </View> <View style={styles.productBox}> <Text style={styles.productName}>Product 2</Text> </View> <View style={styles.productBox}> <Text style={styles.productName}>Product 3</Text> </View> <TouchableOpacity onPress={startAnimation}> <Animated.View style={[styles.animatedContainer, animatedStyle]} > <Text style={styles.productName}>Animated Product</Text> </Animated.View> </TouchableOpacity> </View> ); }; const styles = StyleSheet.create({ container: { flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'space-between', padding: 15, }, productBox: { width: width / 2.2, height: 100, backgroundColor: 'lightgray', marginBottom: 10, alignItems: 'center', justifyContent: 'center', }, productName: { fontSize: 18, fontWeight: 'bold', }, animatedContainer: { width: width / 2.2, height: 100, backgroundColor: 'lightgray', marginBottom: 10, alignItems: 'center', justifyContent: 'center', }, }); export default AnimatedProductList;
2. 检查Babel配置(必填)
确保babel.config.js中添加了Reanimated的插件,这是v3运行的必要条件:
module.exports = { presets: ['module:metro-react-native-babel-preset'], plugins: ['react-native-reanimated/plugin'], };
3. 重新构建项目
完成上述修改后,执行以下操作确保生效:
- 清除缓存:
npm start --reset-cache - 重新安装依赖(可选):
rm -rf node_modules && npm install - iOS:
cd ios && pod install && cd .. - Android:
cd android && ./gradlew clean && cd .. - 重新启动项目
关键API说明
useSharedValue:创建可在UI/JS线程共享的动画状态值,替代旧版ValuewithTiming:生成基于时间的过渡动画,替代旧版timing函数useAnimatedStyle:生成动态绑定动画值的样式,确保样式更新在UI线程执行runOnUI:将动画逻辑切换到UI线程执行,避免JS线程阻塞影响流畅度
内容的提问来源于stack exchange,提问作者BATU
相关产品推荐
相关产品推荐

