


How to make navigation in React-Native? Details of react-native navigation bar production (complete code attached)
This article mainly introduces the function of react-native navigation and how to use react to make it navigable. Then read the following article
1. Navigation functions that are indispensable for every App
We know that whether it is bottom Button switching or page jumps, they are collectively called navigation functions. With these functions, a complete App The basic skeleton will come out, and then the entire skeleton can be filled with business logic. In React-Native, Facebook has also launched navigation components. However, the performance of complex business logic is relatively poor, so the third-party The navigation component react-navigation was born, and Facebook also recommended the use of this component. It can be seen that this navigation component has superior capabilities. This component mainly includes three core functional components: TabNavigator, StackNavigator, and DrawerNavigation. The functions implemented respectively: Tab navigation, page jump , drawer effect (side sliding menu), only the first two components are recorded today.
2. The target effect to be achieved this time
What we want to achieve this time is the two screenshots above. There are three screenshots at the bottom of the main interface. A Tab to switch the navigation of the main interface. The homepage simulation provides an entrance to the secondary page and the second screenshot effect. Next, use code to implement it.
3. Preliminary exploration of react-navigation using TabNavigator
1. Installation
Installation: npm install –save react-navigation -save
After installation, check the value corresponding to dependencies in the package.json file. There will be an additional key-value corresponding to react-navigation and version number: You can also check react- in the node_modules folder in the root directory. navigation component package, if you have it, you can basically be sure that the installation is successful.
2. Routing configuration
Personally, I think the Tab navigation in RN is easier to operate than Android. RN configures the page switching target corresponding to each Tab by itself. Everything must be configured by yourself. After the basic framework is configured, it can be used everywhere. Let’s first conquer the bottom Tab switching function. (If you want to see more, go to the PHP Chinese website React Reference Manual column to learn)
Interface analysis:
The three Tab buttons at the bottom (implemented using TabNavigator)
Each Tab corresponds to three different pages (three pages need to be prepared)
Based on the above simple analysis, we first create three pages. I named them as: MainPage, SettingPage, and MinePage, which correspond to: Homepage, Settings, and My.
MainPage.js
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, Image, View, TouchableOpacity } from 'react-native'; export default class MinePage extends Component { // 此处设置 Tab 的名称和一些样式,这里的会覆盖掉配置路由文件的样式,下面会讲 static navigationOptions = { headerTitle: '首页', tabBarLabel: '首页', tabBarIcon:<Image style={{height: 30, width: 30}} source={require('./ic_tab_mine.png')}/> }; render() { const { navigate } = this.props.navigation; return ( <View style={styles.container}> <Text>首页界面</Text> </View> ); } }const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#F5FCFF', }, });
The other two pages can be deduced by analogy.
After the page is prepared, create the Tab navigation routing configuration file and name it: MyNavigators.js
import React from 'react'; import {StackNavigator, TabNavigator} from 'react-navigation'; import MainPage from '../pages/MainPage'; // 首页import SettingPage from '../pages/SettingPage'; // 设置页面import MinePage from '../pages/MinePage'; // 我的页面import DetailsPage from '../pages/DetailsPage'; // 详情页// 注册tabsconst Tabs = TabNavigator({ Home: { screen: MainPage, }, Set: { screen: SettingPage, }, Me: { screen: MinePage, } }, { animationEnabled: false, // 切换页面时是否有动画效果 tabBarPosition: 'bottom', // 显示在底端,android 默认是显示在页面顶端的 swipeEnabled: false, // 是否可以左右滑动切换tab backBehavior: 'none', // 按 back 键是否跳转到第一个Tab(首页), none 为不跳转 tabBarOptions: { activeTintColor: '#ff8500', // 文字和图片选中颜色 inactiveTintColor: '#999', // 文字和图片未选中颜色 showIcon: true, // android 默认不显示 icon, 需要设置为 true 才会显示 indicatorStyle: { height: 0 // 如TabBar下面显示有一条线,可以设高度为0后隐藏 }, style: { backgroundColor: '#fff', // TabBar 背景色 }, labelStyle: { fontSize: 14, // 文字大小 }, }, }); export default StackNavigator({ Main: { screen: Tabs }, DetailsPage: { // 详情页 screen: DetailsPage }, }, { headerMode: 'screen', // 标题导航 initialRouteName: 'Main', // 默认先加载的页面组件 mode: 'modal' // 定义跳转风格(card、modal) });
Register TabNavigator to receive two parameters (Tab target Page, some tab styles), the target page can be imported just prepared, and the style can be defined according to needs.
Configure the page component stack routing function StackNavigator. Note that all page components in the App must be configured here, just like registering all activities in the manifest file in Android.
Note again: As a whole component, Tab should configure all corresponding pages here in the form of page components.
To get started, in order to improve the readability of the project code logic, I first created a separate App.js file, and then put the routing component I just created separately.
import React, {Component} from 'react';import MyNavigators from './src/navigators/MyNavigators'; export default class App extends Component { render() { return ( // 路由组件 <MyNavigators/> ); } }
Modify the index.js file to load the App.js file after the program starts.
import { AppRegistry } from 'react-native';import App from './App'; AppRegistry.registerComponent('AbcAPP', () => App);
Now run the program and you will see that the bottom navigation Tab has been loaded.
3. Preliminary exploration of react-navigation using StackNavigator to jump to the secondary page
As long as the component is registered in StackNavigator, it will have this attribute navigation, and there is a navigation(str,prm) in this attribute ) method, the first parameter is the name of the target component ( The name is a custom name registered in the routing configuration file, don’t confuse it with the file name) The second parameter can be passed or not. If both When two page components need to communicate, for example, when jumping with parameters, you can use the second parameter to pass the value in the format of key-value. For example, the rendering is as follows:
MainPage.js file
import React, { Component } from 'react'; import { StyleSheet, Text, View, Image, TouchableOpacity } from 'react-native'; export default class MainPage extends Component { static navigationOptions = { // headerTitle:'首页', tabBarLabel: '首页', // headerTitleStyle:{ // fontSize:18, // fontWeight:'400', // alignSelf:'center', // }, headerStyle: { height: 0, //去掉标题 }, tabBarIcon:<Image style={{height: 30, width: 30}} source={require('./ic_tab_mine.png')}/> }; render() { // 获取 navigate 属性 const { navigate } = this.props.navigation; return ( <View style={styles.container}> // 跳转到详情页,并传递两个数据 title、des。 <TouchableOpacity style={{width:200,height: 50, backgroundColor: 'red', borderRadius:5,justifyContent: 'center', alignItems: 'center'}} onPress={() => navigate('DetailsPage', { title: '详情页',des:'回到上一页' })} > <Text style={{color:"#FFF"}}>点击查看详情</Text> </TouchableOpacity> </View> ); } }const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#F5FCFF', justifyContent: 'center', alignItems: 'center' }, });
DetailsPage.js file (remember to register the details page component in MyNavigators.js)
import React, {Component} from 'react'; import { StyleSheet, Text, View, TouchableOpacity } from 'react-native'; export default class DetailsPage extends Component { //接收上一个页面传过来的title显示出来 static navigationOptions = ({navigation}) => ({ headerTitle: navigation.state.params.title, headerTitleStyle:{ fontSize:18, fontWeight:'400', alignSelf:'center' }, headerStyle: {height: 65, backgroundColor: '#FFF'}, headerRight: <View><Text style={{paddingRight: 14, color: '#000', fontSize: 18}}>编辑</Text></View>, headerBackTitle: '回去', headerTruncatedBackTitle: '返回' }); // 点击返回上一页方法 backFunction= () => { //返回首页方法 navigation属性中的自带的返回方法 this.props.navigation.goBack(); } render() { return ( <View style={styles.container}> <TouchableOpacity style={{width:200,height: 50, backgroundColor: 'green', borderRadius:5,justifyContent: 'center', alignItems: 'center'}} onPress={() => { this.backFunction() }}> <Text style={{color:"#FFF"}}>{this.props.navigation.state.params.des}</Text> </TouchableOpacity> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#F5FCFF', alignItems:'center', justifyContent:'center' }, });
After recording, use the above The obtained attribute values, styles, etc. can be Baidu online. Finally, the project structure directory is given:
This article ends here (if you want to see more, go to the PHP Chinese website React User Manual column to learn). If you have any questions, you can leave a message below.
The above is the detailed content of How to make navigation in React-Native? Details of react-native navigation bar production (complete code attached). For more information, please follow other related articles on the PHP Chinese website!

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version
Visual web development tools

Atom editor mac version download
The most popular open source editor