You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native抽屉导航代码报错:java.lang.NoSuchMethodError求助

解决React Navigation抽屉导航报错:Exception in HostFunction: java.lang.NoSuchMethodError: no non-static method

刚上手React Native开发,用React Navigation官网的抽屉导航示例代码时遇到这个错误,先贴出代码:

import * as React from 'react';
import { Button, View } from 'react-native';
import { createDrawerNavigator } from '@react-navigation/drawer';
import { NavigationContainer } from '@react-navigation/native';

function HomeScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Button
        onPress={() => navigation.navigate('Notifications')}
        title="Go to notifications"
      />
    </View>
  );
}

function NotificationsScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Button onPress={() => navigation.goBack()} title="Go back home" />
    </View>
  );
}

const Drawer = createDrawerNavigator();

export default function App() {
  return (
    <NavigationContainer>
      <Drawer.Navigator initialRouteName="Home">
        <Drawer.Screen name="Home" component={HomeScreen} />
        <Drawer.Screen name="Notifications" component={NotificationsScreen} />
      </Drawer.Navigator>
    </NavigationContainer>
  );
}

这个错误大多是依赖版本不兼容或者原生库安装配置问题,试试下面这些方案:

  • 核对依赖版本匹配度:React Navigation的各个包(@react-navigation/native、@react-navigation/drawer)和react-native、react-native-reanimated、react-native-gesture-handler的版本必须对应。比如@react-navigation/drawer对reanimated的版本有要求,确认后重新执行npm install或yarn install。
  • 重新安装react-native-reanimated:抽屉导航依赖这个库,安装异常很容易触发错误:
    npm uninstall react-native-reanimated
    npm install react-native-reanimated
    
    还要在babel.config.js里添加插件(必须放在最后):
    module.exports = {
      presets: ['module:metro-react-native-babel-preset'],
      plugins: ['react-native-reanimated/plugin'],
    };
    
  • 清理缓存后重建:
    • 重置metro缓存:npx react-native start --reset-cache
    • 清理Android构建缓存:进入android目录执行./gradlew clean,再重新运行npx react-native run-android
  • 检查react-native-gesture-handler配置:新版本可能自动配置,但如果是旧项目,要确认MainActivity.java里已经正确导入并初始化这个库。
  • 确认Java版本:Android构建建议用Java 11或17,版本过低可能导致方法找不到的问题。

内容的提问来源于stack exchange,提问作者kursad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 00:52:31