前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >react-native导航组件

react-native导航组件

作者头像
kongxx
发布2024-06-17 09:46:08
790
发布2024-06-17 09:46:08
举报

创建工程

代码语言:javascript
复制
$ npx react-native init MyReactNativeApp

安装react-native navigation和依赖库

代码语言:javascript
复制
$ cd MyReactNativeApp

$ npm install @react-navigation/native
$ npm install @react-navigation/native-stack
$ npm install @react-navigation/stack

$ npm install react-native-gesture-handler react-native-pager-view react-native-paper react-native-reanimated react-native-safe-area-context react-native-screens react-native-tab-view

$ npm install @react-navigation/bottom-tabs @react-navigation/drawer @react-navigation/elements @react-navigation/material-bottom-tabs @react-navigation/material-top-tabs
代码语言:javascript
复制
$ cd ios

$ npx pod-install ios

导航代码

创建 src/navigation.js 文件,在其中添加一个导航器组件,以及两个屏幕组件 HomeScreen 和 ProfileScreen。同时在这两个屏幕组件中添加一个按钮,用于导航到另一个屏幕组件。

代码语言:javascript
复制
import { StyleSheet, Text, View, Button } from 'react-native'
import React from 'react'
import { NavigationContainer } from '@react-navigation/native'
import { createNativeStackNavigator } from '@react-navigation/native-stack'

function HomeScreen(props) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Home Screen</Text>
      <Button title="Go to Profile" onPress={() => props.navigation.navigate('Profile')} />
    </View>
  )
}

function ProfileScreen(props) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Profile Screen</Text>
      <Button title="Go to Home" onPress={() => props.navigation.navigate('Home')} />
    </View>
  )
}

const Stack = createNativeStackNavigator()

export default function index() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Home">
        <Stack.Screen name="Home" component={HomeScreen} options={{ title: 'Home' }} />
        <Stack.Screen name="Profile" component={ProfileScreen} options={{ title: 'Profile' }} />
      </Stack.Navigator>
    </NavigationContainer>
  )
}

修改 App.tsx 文件,添加 NavigationContainer 组件

代码语言:javascript
复制
import React from 'react';
import { SafeAreaView, View, StyleSheet, StatusBar } from 'react-native';
import MyNavigation from './src/navigation'

function App(): React.JSX.Element {

  return (
    <View style={styles.container}>
      <MyNavigation />
    </View>
  )
}

var styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#ffffff',
  }
})

export default App

运行

代码语言:javascript
复制
$ npx react-native start
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-06-16,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 创建工程
  • 安装react-native navigation和依赖库
  • 导航代码
  • 运行
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档