iOS端_reactnativereanimated.default.Value非构造函数报错修复

问题描述
React Native项目接入drawer navigation(抽屉导航)功能时运行异常,iOS端报错信息:
_reactnativereanimated.default.Value is not a constructor
问题根因
项目安装的react-native-reanimated版本为3.0.0-rc.0预览版,该版本已完全移除v1/v2版本中的类式Value构造器API;但Drawer配置中添加了useLegacyImplementation参数,该旧版实现逻辑依赖Reanimated v2的旧API,二者完全不兼容,因此抛出构造器不存在的错误。同时App.js中多余的import Animated, { Value } from 'react-native-reanimated'导入,在v3版本下本身就会触发报错。
修复步骤
- 删除App.js中多余的Reanimated导入行,即删除
import Animated, { Value } from 'react-native-reanimated',当前代码逻辑未使用该部分导入内容。 - 移除
Drawer.Navigator组件上的useLegacyImplementation属性,@react-navigation/drawerv6.4+版本默认已使用兼容Reanimated v3的新实现,无需开启旧版兼容模式。 - 检查Reanimated的babel配置:打开项目根目录的
babel.config.js,确认plugins数组中已添加reanimated插件,且该插件必须放在plugins数组的最后一位,配置参考如下:
module.exports = { presets: ['module:metro-react-native-babel-preset'], plugins: [ 'react-native-reanimated/plugin', ], };
- 清理缓存重新运行项目,依次执行以下命令:
# 清理metro打包缓存 npx react-native start --reset-cache # 进入ios目录执行pod依赖安装 cd ios && pod install && cd .. # 重新运行iOS项目 npx react-native run-ios
修复后参考代码
App.js
import * as React from 'react'; import { View, Text, Button } from 'react-native'; import { NavigationContainer, DrawerActions } from '@react-navigation/native'; import { createDrawerNavigator, DrawerContentScrollView, DrawerItemList, DrawerItem, } from '@react-navigation/drawer'; function Feed({ navigation }) { return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <Text>Feed Screen</Text> <Button title="Open drawer" onPress={() => navigation.dispatch(DrawerActions.openDrawer())} /> <Button title="Toggle drawer" onPress={() => navigation.dispatch(DrawerActions.toggleDrawer())} /> </View> ); } function Notifications() { return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <Text>Notifications Screen</Text> </View> ); } function CustomDrawerContent(props) { return ( <DrawerContentScrollView {...props}> <DrawerItemList {...props} /> <DrawerItem label="Close drawer" onPress={() => props.navigation.dispatch(DrawerActions.closeDrawer())} /> <DrawerItem label="Toggle drawer" onPress={() => props.navigation.dispatch(DrawerActions.toggleDrawer())} /> </DrawerContentScrollView> ); } const Drawer = createDrawerNavigator(); function MyDrawer() { return ( <Drawer.Navigator drawerContent={(props) => <CustomDrawerContent {...props} />} > <Drawer.Screen name="Feed" component={Feed} /> <Drawer.Screen name="Notifications" component={Notifications} /> </Drawer.Navigator> ); } export default function App() { return ( <NavigationContainer> <MyDrawer /> </NavigationContainer> ); }
index.js(原有配置无问题,仅作参考)
/** * @format */ import 'react-native-gesture-handler'; import {AppRegistry} from 'react-native'; import App from './App'; import {name as appName} from './app.json'; AppRegistry.registerComponent(appName, () => App);
内容的提问来源于stack exchange,提问作者Ram01
相关产品推荐
相关产品推荐

