如何避免 createStackNavigator 导致 react-native 应用程序崩溃?
我正在尝试使用 createStackNavigator 实现基本的堆栈导航:
App.js
import { createStackNavigator } from '@react-navigation/stack';
const Stack = createStackNavigator();
function MyStack() {
return (
<Stack.Navigator>
<Stack.Screen name="Home" component={Home} />
<Stack.Screen name="Notifications" component={Notifications} />
<Stack.Screen name="Profile" component={Profile} />
<Stack.Screen name="Settings" component={Settings} />
</Stack.Navigator>
);
}
当我在 Mac(Big Sur)上运行此程序时,Metro 控制台中出现此错误:
[Mon Jan 25 2021 19:21:42.268] BUNDLE ./index.js
[Mon Jan 25 2021 19:21:44.595] ERROR TypeError: null is not an object (evaluating '_RNGestureHandlerModule.default.Direction')
[Mon Jan 25 2021 19:21:44.596] ERROR Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication)
[Mon Jan 25 2021 19:21:45.600] ERROR Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication)
这是我的 package.json:
{
"name": "stack_navigation",
"version": "0.0.1",
"private": true,
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"start": "react-native start",
"test": "jest",
"lint": "eslint ."
},
"dependencies": {
"@react-navigation/stack": "^5.14.2",
"react": "16.13.1",
"react-native": "0.63.4"
},
"devDependencies": {
"@babel/core": "7.12.10",
"@babel/runtime": "7.12.5",
"@react-native-community/eslint-config": "1.1.0",
"babel-jest": "25.5.1",
"eslint": "6.8.0",
"jest": "25.5.4",
"metro-react-native-babel-preset": "0.59.0",
"react-test-renderer": "16.13.1"
},
"jest": {
"preset": "react-native"
}
}
我可以做些什么来使用 createStackNavigator 而不会崩溃?
在 react-navigation 安装指南 中,他们提到,使用 react navigation 时还必须安装一些其他依赖项。
因此,首先使用 react-natvigation 安装这些库:
npm install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view
如果您使用的是 Android,自动链接将自动完成,如果您使用的是 iOS,则必须运行:
pod install
现在,在您的应用程序文件顶部导入
react-native-gesture-handle
,例如在 app.js 或 index.js 中:
import 'react-native-gesture-handler';
正如文档所述,您必须执行此操作,您不能跳过此安装如果您正在为 Android 或 iOS 构建应用程序,则请执行以下步骤:
Note: If you are building for Android or iOS, do not skip this step, or your app may crash in production even if it works fine in development. This is not applicable to other platforms.
最后,您需要将整个应用程序包装在 NavigationContainer 中。通常您会在入口文件中执行此操作,例如 index.js 或 App.js:
import 'react-native-gesture-handler';
import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
export default function App() {
return (
<NavigationContainer>{/* Rest of your app code */}</NavigationContainer>
);
}
如果 app.js 文件中不存在组件,则必须导入这些组件。此外,您还需要一个 navigationContainer 来包装 app.js 代码,以指示这些区域可以导航。当然,您需要一个事件来导航,也许是一个按钮,触发事件,并且您需要一个函数。因此,文档中的
navigation.navigate
不起作用,但是当您将其更改为
push
时,它就可以工作。但是,它只是将另一个屏幕推送到您的堆栈。您无法在您创建的现有屏幕之间导航。我建议您使用 react-router。也许使用旧版本的 react-nav。v5 似乎已损坏。