Home  >  Article  >  Web Front-end  >  How to make navigation in React-Native? Details of react-native navigation bar production (complete code attached)

How to make navigation in React-Native? Details of react-native navigation bar production (complete code attached)

寻∝梦
寻∝梦Original
2018-09-11 14:27:062727browse

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

How to make navigation in React-Native? Details of react-native navigation bar production (complete code attached)How to make navigation in React-Native? Details of react-native navigation bar production (complete code attached)

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:
How to make navigation in React-Native? Details of react-native navigation bar production (complete code attached)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:

  1. The three Tab buttons at the bottom (implemented using TabNavigator)

  2. 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(&#39;./ic_tab_mine.png&#39;)}/>
    };
    render() {        const { navigate } = this.props.navigation;        return (
            <View style={styles.container}>
                <Text>首页界面</Text>
            </View>
        );
    }
}const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: &#39;#F5FCFF&#39;,
    },
});

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 &#39;react&#39;;
import {StackNavigator, TabNavigator} from &#39;react-navigation&#39;;
import MainPage from &#39;../pages/MainPage&#39;;   // 首页import SettingPage from &#39;../pages/SettingPage&#39;;   // 设置页面import MinePage from &#39;../pages/MinePage&#39;;          // 我的页面import DetailsPage from &#39;../pages/DetailsPage&#39;;     // 详情页// 注册tabsconst Tabs = TabNavigator({
    Home: {
        screen: MainPage,
    },
    Set: {
        screen: SettingPage,
    },
    Me: {
        screen: MinePage,
    }
}, {
    animationEnabled: false, // 切换页面时是否有动画效果
    tabBarPosition: &#39;bottom&#39;, // 显示在底端,android 默认是显示在页面顶端的
    swipeEnabled: false, // 是否可以左右滑动切换tab
    backBehavior: &#39;none&#39;, // 按 back 键是否跳转到第一个Tab(首页), none 为不跳转
    tabBarOptions: {
        activeTintColor: &#39;#ff8500&#39;, // 文字和图片选中颜色
        inactiveTintColor: &#39;#999&#39;, // 文字和图片未选中颜色
        showIcon: true, // android 默认不显示 icon, 需要设置为 true 才会显示
        indicatorStyle: {
            height: 0  // 如TabBar下面显示有一条线,可以设高度为0后隐藏
        },
        style: {
            backgroundColor: &#39;#fff&#39;, // TabBar 背景色
        },
        labelStyle: {
            fontSize: 14, // 文字大小
        },
    },
});
export default StackNavigator({
        Main: {
            screen: Tabs
        },
        DetailsPage: { // 详情页
            screen: DetailsPage
        },
    },
    {
        headerMode: &#39;screen&#39;,  // 标题导航
        initialRouteName: &#39;Main&#39;, // 默认先加载的页面组件
        mode: &#39;modal&#39;       // 定义跳转风格(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 &#39;react&#39;;import MyNavigators from &#39;./src/navigators/MyNavigators&#39;;
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 &#39;react-native&#39;;import App from &#39;./App&#39;;
AppRegistry.registerComponent(&#39;AbcAPP&#39;, () => 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 &#39;react&#39;;
import {
    StyleSheet,
    Text,
    View,
    Image,
    TouchableOpacity
} from &#39;react-native&#39;;
export default class MainPage extends Component {
    static navigationOptions = {        // headerTitle:&#39;首页&#39;,
        tabBarLabel: &#39;首页&#39;,        // headerTitleStyle:{
        //     fontSize:18,
        //     fontWeight:&#39;400&#39;,
        //     alignSelf:&#39;center&#39;,
        // },
        headerStyle: {
            height: 0, //去掉标题
        },
        tabBarIcon:<Image style={{height: 30, width: 30}}
                          source={require(&#39;./ic_tab_mine.png&#39;)}/>
    };
    render() {        // 获取 navigate 属性
        const { navigate } = this.props.navigation;        return (
            <View style={styles.container}>                // 跳转到详情页,并传递两个数据 title、des。
                <TouchableOpacity style={{width:200,height: 50, backgroundColor: &#39;red&#39;, borderRadius:5,justifyContent: &#39;center&#39;, alignItems: &#39;center&#39;}}
                                  onPress={() => navigate(&#39;DetailsPage&#39;, { title: &#39;详情页&#39;,des:&#39;回到上一页&#39; })} >
                    <Text style={{color:"#FFF"}}>点击查看详情</Text>
                </TouchableOpacity>
            </View>
        );
    }
}const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: &#39;#F5FCFF&#39;,
        justifyContent: &#39;center&#39;,
        alignItems: &#39;center&#39;
    },
});

DetailsPage.js file (remember to register the details page component in MyNavigators.js)

import React, {Component} from &#39;react&#39;;
import {
    StyleSheet,
    Text,
    View,
    TouchableOpacity
} from &#39;react-native&#39;;
export default class DetailsPage extends Component {
    //接收上一个页面传过来的title显示出来
    static navigationOptions = ({navigation}) => ({
        headerTitle: navigation.state.params.title,
        headerTitleStyle:{
            fontSize:18,
            fontWeight:&#39;400&#39;,
            alignSelf:&#39;center&#39;
        },
        headerStyle: {height: 65, backgroundColor: &#39;#FFF&#39;},
        headerRight: <View><Text style={{paddingRight: 14, color: &#39;#000&#39;, fontSize: 18}}>编辑</Text></View>,
        headerBackTitle: &#39;回去&#39;,
        headerTruncatedBackTitle: &#39;返回&#39;
    });    // 点击返回上一页方法
    backFunction= () => {        //返回首页方法 navigation属性中的自带的返回方法
        this.props.navigation.goBack();
    }
    render() {        return (
            <View style={styles.container}>
                <TouchableOpacity
                    style={{width:200,height: 50, backgroundColor: &#39;green&#39;, borderRadius:5,justifyContent: &#39;center&#39;, alignItems: &#39;center&#39;}}
                    onPress={() => {                        this.backFunction()
                    }}>
                    <Text style={{color:"#FFF"}}>{this.props.navigation.state.params.des}</Text>
                </TouchableOpacity>
            </View>
        );
    }
}
const styles = StyleSheet.create({    container: {
        flex: 1,
        backgroundColor: &#39;#F5FCFF&#39;,
        alignItems:&#39;center&#39;,
        justifyContent:&#39;center&#39;
    },
});

After recording, use the above The obtained attribute values, styles, etc. can be Baidu online. Finally, the project structure directory is given:

How to make navigation in React-Native? Details of react-native navigation bar production (complete code attached)

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn