找了很多資料,看了頭大,去GitHub上搜到了兩個不錯的文檔
https://wix.github.io/react-native-navigation/docs/before-you-start/#!
https://reactnavigation.org/docs/getting-started
前置內容:react native 環境搭建
1.在本地文件夾內執行
react-native init ReactNativeNavigation
init後面的名字可以自己取,執行完畢的效果就是在本地新建一個名爲ReactNativeNavigation的目錄。裏面是自動生成的項目
打開android studio,點擊工具欄的file,打開此目錄下的android文件夾,然後點擊執行按鈕
這時彈出模擬器窗口,結果如下:
說明第一步沒有問題
2.在ReactNativeNavigation目錄下在命令提示符執行
npm install @react-navigation/native
npm install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view
3.修改ReactNativeNavigation目錄下的App.js文件,內容如下:
import { NavigationContainer } from '@react-navigation/native';
import React ,{
Component
} from 'react';
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
StatusBar,
} from 'react-native';
import {
Header,
LearnMoreLinks,
Colors,
DebugInstructions,
ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';
export default class App extends Component {
constructor(props) {
super(props);
}
render(){
return <Text>hello</Text>
}
}
模擬器效果如下:
現在按照文檔的內容,在App.js寫入
import 'react-native-gesture-handler';
這時報錯了:
TypeError:null is not an object (evaluating '_RNGestureHandlerModule.default.Direction'))
執行
react-native link react-native-gesture-handler
仍舊沒有什麼用
而且說明了高版本的不用link
From React Native 0.60 and higher, linking is automatic. So you don't need to run react-native link
.
卡了兩天了,跳過吧
修改App.js的內容
import * as React from 'react';
import { View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
function HomeScreen() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
</View>
);
}
const Stack = createStackNavigator();
function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
export default App;
報錯:undefined Unable to resolve module '@react-navigation/stack' from 'App.js'
那麼就安裝這個模塊吧
npm install @react-navigation/stack
仍舊不起作用。
最後 android studio中Http proxy選擇no proxy
File->Invalidate Caches->Invalidate and Restart
打開gradle.properties文件,路徑在C:\Users\你的用戶名\.gradle\gradle.properties
註釋掉裏面的proxy設置
然後react-native start
react-native run-android
結果如下:
不容易啊