環(huán)境要求
-
react-native
>= 0.63.0 -
expo
>= 41(如果您使用世博會(huì)) -
typescript
>= 4.1.0(如果您使用TypeScript)
使用(mac)
1.核心包
npm install @react-navigation/native
或者
yarn add @react-navigation/native
2.依賴項(xiàng)目
npm install react-native-screens react-native-safe-area-context
或者
yarn add react-native-screens react-native-safe-area-context
3.ios特殊操作
npx pod-install ios
4.使用 createNativeStackNavigator 基礎(chǔ)導(dǎo)航器 前置安裝
npm install @react-navigation/native-stack
5 .使用createNativeStackNavigator 具體
1)導(dǎo)入
import {NavigationContainer} from '@react-navigation/native'
import {createNativeStackNavigator} from '@react-navigation/native-stack'
2)定義導(dǎo)航
createStackNavigator(
{
Home : HomeScreen, // 路由:組件
Detail : DetailScreen // 路由:組件
},{
initialRouteName:'Home'
}
)
3)NavigationContainer 函數(shù)對(duì) createNativeStackNavigator 進(jìn)行包裹
4)導(dǎo)出createNativeStackNavigator創(chuàng)建組件,作為應(yīng)用程序的根組件
5)onPress事件 調(diào)用 navigaition.navigate(路由名稱)方法
<Button
title="Go to Details"
onPress={() => this.props.navigation.navigate('Details')}
/>
6) 參數(shù)的傳遞
a.傳遞
(1)參數(shù)包裝一個(gè)對(duì)象
(2)把對(duì)象 通過(guò) navigation.navigate(RouteName,{params go here}) 的第二個(gè)參數(shù)
b.讀取
(1)參數(shù)傳遞
class HomeScreen extends React.Component {
render(){
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
<Button
title="Go to Details"
onPress={() => {
let paramsgg = {itemId:87,otherParams:'anything you want here'}
this.props.navigation.navigate('Details',paramsgg)
}}
/>
</View>
);
}
}
class DetailsScreen extends React.Component {
render(){
const {navigation,route} = this.props
console.log(this.props)
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Details Screen</Text>
<Text>ItemId:{route.params.itemId}</Text>
<Text>otherParams:{route.params.otherParams}</Text>
<Button
title="Go to Details... again"
onPress={() => {
navigation.navigate('Details')
}}
/>
</View>
);
}
}