RN react-navigation Use

Source: Internet
Author: User
Tags require
1. Command installation
npm install react-navigation --save
The library contains three types of components:

(1) StackNavigator: used to jump pages and pass parameters

(2) TabNavigator: similar to the bottom navigation bar, used to switch between different pages on the same screen

(3) DrawerNavigator: side-slide menu navigation bar, used to easily set the screen with drawer 2. React-navigation 1. Introduction of StackNavigator properties

navigationOptions: Configure some properties of StackNavigator.

    title: title, if the title of the navigation bar and the tab bar is set to become the same, it is not recommended
    header: You can set some navigation attributes, if you hide the top navigation bar, just set this attribute to null
    headerTitle: set the navigation bar title, recommended
    headerBackTitle: Set the text behind the back arrow on the left side of the jump page. The default is the title of the previous page. Can be customized or set to null
    headerTruncatedBackTitle: When the title of the previous page does not match the text after the return arrow, the default is changed to "back
    headerRight: Set the right side of the navigation bar. Can be buttons or other view controls
    headerLeft: Set the left side of the navigation bar. Can be buttons or other view controls
    headerStyle: Set the style of the navigation bar. Background color, width and height, etc.
    headerTitleStyle: Set the text style of the navigation bar
    headerBackTitleStyle: Set the navigation bar ‘Back’ text style
    headerTintColor: set the navigation bar color
    headerPressColorAndroid: Android unique set color texture, requires Android version greater than 5.0
    gesturesEnabled: Whether to support the slide back gesture, iOS supports it by default, and Android disables it by default
 

screen: corresponding to the interface name, you need to fill in the page after import

mode: defines the jump style

   card: Use the default style of iOS and Android

   modal: iOS unique makes the screen draw from the bottom. Present effect similar to iOS

headerMode: Animation effect when returning to the previous page

   float: iOS default effect

   screen: During the sliding process, the entire page will return

   none: no animation

cardStyle: custom setting jump effect

   transitionConfig: custom settings for sliding return configuration

   onTransitionStart: function called when the transition animation is about to start

   onTransitionEnd: the function that will be called when the transition animation is completed

path: Overlay mapping configuration of the path set in the route

initialRouteName: Set the default page component, which must be the page component registered above

initialRouteParams: initial routing parameters
StackNavigator (RouteConfigs, StackNavigatorConfig)
// Register navigation
const Navs = StackNavigator ({
    Home: {screen: Tabs},
    HomeTwo: {
        screen: HomeTwo, // Required, other are optional
        path: 'app / homeTwo', used when using url navigation, such as web app and Deep Linking
        navigationOptions: {} // If set here, it will override the setting of `static navigationOptions` in the component. For details, see below
    },
    HomeThree: {screen: HomeThree},
    HomeFour: {screen: HomeFour}
}, {
    initialRouteName: 'Home', // default display interface
    navigationOptions: {// The default options for screen navigation, you can also use static navigationOptions in the component (will override the settings here)
     headerTitle: "Home", // Title of navigation bar
     headerBackTitle: null, // Set the text behind the back arrow on the left side of the jump page, the default is the title of the previous page. Can be customized or set to null
     headerTintColor: "# 333", // Set the color of the navigation bar
        cardStack: {
            gesturesEnabled: true // Whether to allow the right slide back, the default is true on iOS, false on Android
        }
    },
    mode: 'card', // page switching mode, left and right are cards (equivalent to push effect in iOS), up and down are modal (equivalent to modal effect in iOS)
    headerMode: 'screen', // The display mode of the navigation bar, screen: with gradient transparency effect, float: no transparency effect, none: hide the navigation bar
    onTransitionStart: () => {console.log ('navigation bar switching start');}, // callback function at the beginning of page switching
    onTransitionEnd: () => {console.log ('navigation bar switching end');} // callback function at the end of page switching
});
If the navigationOptions parameters are configured in StackNavigatorConfig, these parameters will affect all routing subpages in RouteConfigs. If static navigationOptions is set in the routing subpages, it will override the global parameters configured here

The navigator and the corresponding routing page have been configured, but navigation is required to complete the jump between the pages. navigation

Every page in the navigator has a navigation attribute, which has the following attributes / methods:

navigate-jump to another page
state-the state of the current page navigator
setParams-Change the parameters of the route
goBack-back
dispatch-send an action
navigete
Call this method to jump to other pages in the navigator, this method has three parameters: RN react-navigation use

— RouteName The route name configured in the navigator

— Params pass parameters to the next page

— Action action

For example: this.props.navigation.navigate ('Find', {param: 'i am the param'});
RN react-navigation use
  state

The state contains the passed parameters params, key, route name routeName, print log can be seen:

{
  params: {param: 'i am the param'},
  key: 'id-1500546317301-1',
  routeName: 'Mine'
}
  setParams

Change the parameters of the current page routing, such as the button or title that can be used to update the header.

componentDidMount () {
    this.props.navigation.setParams ({param: 'i am the new param'})
}
  goBack

Back, you can not pass, you can also pass parameters, you can also pass null.

this.props.navigation.goBack (); // Back to the previous page
this.props.navigation.goBack (null); // Back to any page
this.props.navigation.goBack ('Home'); // Back to the Home page



2. TabNavigator attribute introduction

screen: It is the same as the navigation function, corresponding to the interface name, you can pass the value and jump on this screen on other pages.


navigationOptions: Configure some properties of TabNavigator

title: Title, the title of the navigation bar and the tab bar will be set at the same time

tabBarVisible: Whether to hide the tab bar. Not hidden by default (true)

tabBarIcon: Set the icon of the tab bar. Need to set for each

tabBarLabel: Set the title of the tab bar. recommend

Navigation bar configuration

tabBarPosition: Set the position of the tabbar, iOS defaults to the bottom, and Android defaults to the top. (Attribute value: 'top', 'bottom')

swipeEnabled: whether to allow swiping between tabs

animationEnabled: whether to show animation when changing the label

lazy: Whether to render the label lazily as needed instead of in advance, which means that the bottom label bar is loaded when the app is opened, the default is false, the recommended is true

trueinitialRouteName: Set the default page component

backBehavior: press the back key to jump to the first Tab (home page), none means no jump

tabBarOptions: Configure some properties of the tab bar iOS properties

activeTintColor: the foreground color of the label and icon in the active state

activeBackgroundColor: the background color of the label and icon in the active state

inactiveTintColor: the foreground color of label and icon is inactive

inactiveBackgroundColor: the background color of label and icon is inactive

showLabel: whether to display the label, the default open style: tabbar style

labelStyle: style Android attributes of label

activeTintColor: the foreground color of the label and icon in the active state

inactiveTintColor: the foreground color of label and icon is inactive

showIcon: whether to display the icon, closed by default

showLabel: whether to display the label, the default open style: tabbar style

labelStyle: label style upperCaseLabel: whether to make the label capitalized, default is true

pressColor: color of material ripple effect (Android version needs to be greater than 5.0)

pressOpacity: the transparency of the press label (Android version needs to be less than 5.0)

scrollEnabled: Whether to enable the scrollable tab tabStyle: the style of the tab

indicatorStyle: The style object of the label indicator (the row at the bottom of the tab). There will be an extra line at the bottom of Android, you can temporarily set the height to 0 to solve this problem

labelStyle: the style of the label

iconStyle: icon style
3. DrawerNavigator property introduction
 DrawerNavigatorConfig

     drawerWidth-the width of the drawer
     drawerPosition-option is left or right. The default is the left position
     contentComponent-The component used to render the content of the drawer, such as navigation items. Receive drawer navigation. The default is DrawerItems
     contentOptions-configure drawer content

     initialRouteName-the routeName of the initial route
     order-an array of routeNames that defines the order of drawer items.
     Path-provides a mapping from routeName to path configuration, which overrides the path set in routeConfigs
     backBehavior-Whether the back button will switch to the initial route. If yes, set to initialRoute, otherwise none. The default is the initialRoute behavior

    DrawerItems con
tentOptions attribute

     activeTintColor-the label and icon color of the active label
     activeBackgroundColor-active label background color
     inactiveTintColor-label and icon color for inactive labels
     inactiveBackgroundColor-background color of inactive label
     Style object for content section
     labelStyle-style object to override the text style in the content section when your label is a string
4. Use StackNavigator + TabNavigator to implement Tab interface switching and navigation between interfaces

1> First import the necessary components (including navigation routing)

import {StackNavigator, TabNavigator, TabBarBottom} from "react-navigation";
import Home from "./category/Home";
import Feedback from "./category/feedback/feedback";
import Task from "./category/task/taskHome";
2> Define TabNavigator

const MyTab = TabNavigator (
    {
        Home: {
            screen: Home,
            navigationOptions: ({navigation}) => ({
                headerTitle: "Home",
                tabBarLabel: "Home",
                headerBackTitle: null,
                tabBarIcon: ({tintColor}) => (
                    <Image
                        style = {styles.imageStyle}
                        source = {
                            tintColor == "# ff552e"
                                ? require ("./ img / yingxiao / ac-jingxuan.png")
                                : require ("./ img / yingxiao / jingxuan.png")
                        }
                    />
                )
            })
        },
        Feed: {
            screen: Feedback,
            navigationOptions: ({navigation}) => ({
                headerTitle: "Feedback",
                tabBarLabel: "mine",
                headerBackTitle: null,
                headerRight: (
                    <Text
                        style = {{color: "# 333", marginRight: 14, fontSize: 16}}
                        onPress = {() =>
                            navigation.state.params? navigation.state.params.submit (): null
                        }>
                        submit
                    </ Text>
                ),
                tabBarIcon: ({tintColor}) => (
                    <Image
                        style = {styles.imageStyle}
                        source = {
                            tintColor == "# ff552e"
                                ? require ("./ img / yingxiao / ac-laidiantong.png")
                                : require ("./ img / yingxiao / laidiantong.png")
                        }
                    />
                )
            })
        }
    },
    {
        tabBarComponent: TabBarBottom,
        tabBarPosition: "bottom", // Set the position of the tabbar, iOS defaults to the bottom, Android defaults to the top. (Attribute value: 'top', 'bottom')
        swipeEnabled: true, // Whether to allow sliding between tags
        animationEnabled: false, // Whether to display animation when changing the label
        lazy: true, // Whether to render the label lazily as needed instead of making it in advance, which means that the bottom label bar is loaded when the app is opened, the default is false, it is recommended to change to true
        tabBarOptions: {
            activeTintColor: "# ff552e", // The foreground color of the label and icon is active (selected)
            // activeBackgroundColor: 'blue', // background color of label and icon is active
            inactiveTintColor: "# 333", // Foreground color of label and icon is inactive
            showLabel: true, // Whether to display the label, open by default
            showIcon: true, // Android does not display icon by default, it needs to be set to true to display
            style: {backgroundColor: "#ffffff"}, // tabbar style
            labelStyle: {
                fontSize: 14 // text size
            }
        }
    }
);
3> Define StackNavigator

Effect picture:

const AppIndex = StackNavigator ({
    Main: {
        screen: MyTab
    },
Task: {
        screen: Task,
        navigationOptions: {
            headerBackTitle: null
        }
    }
});

RN react-navigation use RN react-navigation use

Task system navigation Jump to the task home page:

RN react-navigation use

Difficulties: Navigate to the configuration button on the right:

headerRight: Set the right side of the navigation bar. Can be buttons or other view controls
When using react-navigation, set navigationOptions in a single page, and call the method in Static.
onPress = {() => this.share ()}

static navigationOptions = ({navigation}) => ({
        title: `$ {navigation.state.params.title}`,
        headerBackTitle: `$ {navigation.state.params.title}`,
        headerRight: (
            <View style = {{flexDirection: "row"}}>
                <Text
                    style = {{color: "# 333", marginRight: 13}}
                    // This call method cannot be used in static, and share is not function appears
                    onPress = {() => this.share ()
                    }>
                    share it
                </ Text>
                
            </ View>
        )
    });
Solution:
// Configure two buttons on the right
static navigationOptions = ({navigation}) => ({
        title: `$ {navigation.state.params.title}`,
        headerBackTitle: `$ {navigation.state.params.title}`,
        headerRight: (
            <View style = {{flexDirection: "row"}}>
                <Text
                    style = {{color: "# 333", marginRight: 13}}
                    onPress = {() =>
                        navigation.state.params? navigation.state.params.share (): null
                    }>
                    share it
                </ Text>
                <Text
                    style = {{color: "# 333", marginRight: 13}}
                    onPress = {() =>
                        navigation.state.params? navigation.state.params.jumpToRule (): null
                    }>
                    Exchange Rules
                </ Text>
            </ View>
        )
    });
For example to share:

First declare a share () in this class {

}Methods

After the page is mounted, set na in componentDidMount The setParams of the vigation injects the method into the navigation

componentDidMount () {
         // By setting setParams in componentDidMount
         this.props.navigation.setParams ({
             share: this.share
         });
     }
Then when clicked, look directly in the navigation to find the placement that was just injected and call it directly

onPress = {() =>
                         navigation.state.params? navigation.state.params.share (): null
                     }
The initial processing method in my development:

Put this type of function that the button configured in the navigation needs to call under the window global object, and then find the call in the global

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.