环境要求
-
react-native
>= 0.63.0 -
expo
>= 41(如果您使用世博会) -
typescript
>= 4.1.0(如果您使用TypeScript)
使用(mac)
1.核心包
npm install @react-navigation/native
或者
yarn add @react-navigation/native
2.依赖项目
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 基础导航器 前置安装
npm install @react-navigation/native-stack
5 .使用createNativeStackNavigator 具体
1)导入
import {NavigationContainer} from '@react-navigation/native'
import {createNativeStackNavigator} from '@react-navigation/native-stack'
2)定义导航
createStackNavigator(
{
Home : HomeScreen, // 路由:组件
Detail : DetailScreen // 路由:组件
},{
initialRouteName:'Home'
}
)
3)NavigationContainer 函数对 createNativeStackNavigator 进行包裹
4)导出createNativeStackNavigator创建组件,作为应用程序的根组件
5)onPress事件 调用 navigaition.navigate(路由名称)方法
<Button
title="Go to Details"
onPress={() => this.props.navigation.navigate('Details')}
/>
6) 参数的传递
a.传递
(1)参数包装一个对象
(2)把对象 通过 navigation.navigate(RouteName,{params go here}) 的第二个参数
b.读取
(1)参数传递
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>
);
}
}