本文内容如下
react native导航器的学习,结合typescript使用
如果你都有了答案,可以忽略本文章,或去react native学习导图寻找更多答案
学习官网
学习版本6.x
"dependencies": {
"@react-navigation/bottom-tabs": "^6.0.9",
"@react-navigation/native": "^6.0.6",
"@react-navigation/native-stack": "^6.2.5",
"react": "17.0.2",
"react-native": "0.66.2",
"react-native-gesture-handler": "^1.10.3",
"react-native-safe-area-context": "^3.3.2",
"react-native-screens": "^3.9.0",
"typescript": "^4.4.4"
},
导航安装
一定要安装:
yarn add @react-navigation/native react-native-screens react-native-safe-area-context
@react-navigation/native 导航核心包
react-native-screens 原生组件兼容包
react-native-safe-area-context 安全区域包
根据业务选择安装:
@react-navigation/native-stack 堆栈式导航
@react-navigation/bottom-tabs 标签式导航
@react-navigation/drawer 抽屉式导航
@react-navigation/material-top-tabs react-native-tab-view 顶部标签导航
安装后的配置
在这里插入代码片
堆栈式导航
Navigator -> index.tsx
import * as React from 'react';
import {
NavigationContainer } from '@react-navigation/native';
import {
createNativeStackNavigator,
NativeStackNavigationProp,
} from '@react-navigation/native-stack';
// 组件导入
import {
Home } from '@/pages/Home';
import {
Detail } from '@/pages/Detail';
// typescript相关
// 指定路由和路由参数
export type RootStackParams = {
Home: undefined;
Detail: {
id: number;
};
};
// 用于定义导航器对象
export type RootStackNavigation = NativeStackNavigationProp<RootStackParams>;
// 堆栈式导航,接收泛型参数
const Stack = createNativeStackNavigator<RootStackParams>();
const Navigator = () => {
return (
<NavigationContainer>
<Stack.Navigator
screenOptions={
{
headerShown: true, //导航头是否可见,默认true可见
headerTitleAlign: 'center', //导航头标题显示位置,默认left
gestureEnabled: true,
animation: 'slide_from_right', //当按下或弹出时,屏幕应该如何动画,slide_from_right右进右出
presentation: 'card', //屏幕的呈现方式
}}>
// Stack.Screen两种使用方式
// 1
<Stack.Screen
name="Home"
component={
Home}
options={
{
title: '首页' }}
/>
// 2
<Stack.Screen name="Detail" initialParams={
{
id: 88 }}>
{
props => <Detail {
...props} />}
</Stack.Screen>
</Stack.Navigator>
</NavigationContainer>
);
};
export default Navigator;
配置项
Stack.Navigator 中的 screenOptions 是全局配置,生效于每个页面组件
Stack.Screen 中的 options 是当页配置,只生效于当前页面组件
路由跳转,并传递参数
pages -> home.tsx
路由跳转使用:navigation.navigate,并可以传递参数
使用方式:2种
- props.navigation
- hook:useNavigation
import React from 'react';
import {
View, Text, Button } from 'react-native';
import {
RouteProp, useNavigation } from '@react-navigation/native';
import {
RootStackNavigation, RootStackParams } from '@/navigator/index';
// 导航器会传递两个对象:
// navigation:用于导航跳转,传递参数
// route:用于接收参数
interface IProps {
navigation: RootStackNavigation; //路由对象
route: RouteProp<RootStackParams, 'Home'>; //路由参数,第一个参数是类型,第二个参数是页面
}
export const Home = ({
navigation