This is the 15th day of my participation in the August More text Challenge. For details, see: August More Text Challenge
The react-Navigation library has been officially discontinued since version 0.43, so we strongly recommend that you move to the new React-Navigation library. And the new navigation library is much better than the old Navigator in terms of performance and ease of use!
The English document address is attached.
Here is an example of my own navigation :github.com/lizhuoyuan/…
It is recommended to look directly at the example with clear notes. The logic is easy to understand
Let’s look at react-Navigation.
A StackNavigator
1. Download and install
Execute at the project root directory:
npm install –save react-navigation
2. Introduce the components we need in the JS file
import {StackNavigator} from ‘react-navigation’;
3. Start using it
import Home from './Home';
import Mains from './Second'
const App = StackNavigator({
Home: {screen: Home},
Chat: {screen: Second},
Two: {screen: Mains}
});
export default App;
Copy the code
Introduce the app in index.android.js or index.ios.js
Add the pages we need to jump to in the StackNavigator.
Then set a title for each page
export default class Home extends React.Component {
static navigationOptions = {
title: 'Welcome',
};
Copy the code
The word “Welcome” appears in the title bar.
Next up is the jump
Use the navigate() method to perform the jump
navigate(‘Chat’, {user:user})
The name of the page defined by chat, followed by {}, which contains the parameters you want to pass, can be empty,
For example, navigate (‘ Chat ‘),
The code is as follows:
render() {
const {navigate} = this.props.navigation;
let user = {'name': 'zy', age: 18}
return (
<View>
<Text onPress={() => navigate('Chat', {user:user})}>Home</Text>
</View>
)
}
}
Copy the code
How to write the receive parameters on the Chat page:
render() {
const {navigate} = this.props.navigation;
let {params} = this.props.navigation.state;
return (
<View>
<Text>Second {params.user.name}</Text>
</View>
)
}
Copy the code
In this way, the text component will display the argument that you passed in. For example, if I passed in an object with name ZY, then it will display Second ZY.
If you jump from the first page to the second page, the second page will have a fallback button to return to the previous page.
class Second extends React.Component { static navigationOptions = ({navigation}) => ({ title: ` ${navigation. State. Params. User. The name} `, / / the name attribute of the object before a page from the}) render () {const {navigate} = this. Props. The navigation; let {params} = this.props.navigation.state; return ( <View> <Text onPress={() => navigate('Home')}>Second {params.user.name}</Text> </View> ) } } class Three extends React.Component { static navigationOptions = ({navigation}) => ({ title: ` ${navigation.state.params.user.age}`, }) render() { const {navigate} = this.props.navigation; let {params} = this.props.navigation.state; var name = params.name; return ( <View> <Text>three : {params.user.age}</Text> </View> ) } } const MainSceen = TabNavigator({ l1: {screen: Second}, l2: {screen: Three} }) export default MainSceen;Copy the code
Of course, after we do that we add the MainSceen component to our StackNavigator,
Like this:
const App = StackNavigator({
Home: {screen: Home},
// Chat: {screen: Second},
Two: {screen: Mains}
});
Copy the code
Direct navigate(‘Two’) is fine, if you do not need to pass the parameters.
Then we add a button to the right of the title bar
static navigationOptions = ({navigation}) => ({ title: ` ${navigation. State. Params. User. The name} `, headerRight: < Button title = {} 'title' / >})Copy the code
Of course, you can replace it with other components, add click events, etc. You can also match them together.
This navigationOptions can also be configured in the original StackNavigator:
const App = StackNavigator({ Home: { screen: Home, navigationOptions: { headerTitle: HeaderTitleStyle: {color: 'red', backgroundColor: 'white', alignSelf: 'center'}, // Set the title bar text style to center headerStyle: {backgroundColor: 'green'}, // The navigation bar style //header: NULL // Hide the navigation bar headerRight: <Text onPress={() => { alert('i am right'); </Text> < img style={{marginLeft: 10}}> </Text>, First: {screen: {screen:} First, navigationOptions: ({navigation}) => ({ headerTitle: 'i am first', headerStyle: {backgroundColor: HeaderTitleStyle: {color: 'red', alignSelf: 'center', backgroundColor: 'white'}, headerLeft: <Button title={'go back'} onPress={() => { navigation.goBack(); }}/>, }) }, Second: { screen: Second, navigationOptions: {} }, Tab: { screen: Tab, navigationOptions: { title: 'Tab', } }, });Copy the code
In the generic properties above, a right button is configured, so there will be one on every page
Its properties are:
StackNavigatorConfig
Router options:
initialRouteName
– Sets the default screen for the stack. A key in the route configuration must be matched. It is the name of an existing routeinitialRouteParams
– Parameters of the initial routenavigationOptions
– Default navigation option for the screenpaths
– Overlay mapping of the path specified in route configuration
Visual options:
-
Mode – Defines the rendering and transformation styles:
card
– Use standard iOS and Android screen conversion. This is the default.modal
– Make the screen slide in from the bottom, this is normal iOS mode. IOS only, no impact on Android.
-
HeaderMode – Specifies how the title should be rendered:
float
– Render a title that stays at the top and animates as the screen changes. This is a common pattern on iOS.screen
– Each screen has a title that fades in and out with the screen. This is a common pattern on Android.none
– Title will not be displayed.
-
CardStyle – Use this branch to override or extend the default style of individual cards in the stack.
-
TransitionConfig – Returns the ability to override the default screen conversion object.
-
OnTransitionStart – The function called when the card transition animation is about to start.
-
OnTransitionEnd – The function to be called after the card transition animation has completed.
Next, look at the navigationOptions parameters:
title
String can be used as a fallback and headerTitle tabBarLabel
header
React element or the given function returns a React element with display as the title. Set the hidden title. HeaderProps“null
headerTitle
The string or React element used for the title. The default is scenario title
headerBackTitle
The back button on iOS uses a title string or disable label. The default is scenario NULL title
headerTruncatedBackTitle
The title string to use when the back button does not fit on the screen. The default. headerBackTitle“”Back”
headerRight
The reaction element is displayed on the right side of the heading
headerLeft
The reaction element is displayed to the left of the title
headerStyle
Style object for the title
headerTitleStyle
Style object for the title component
headerBackTitleStyle
The style object is the title that follows
headerTintColor
The title color
headerPressColorAndroid
Color textures (Android> = 5.0)
GesturesEnabled #
Whether you can use gestures to close this screen. It defaults to true on iOS and false on Android.
2. TabNavigator
Then let’s look at the use of another common component, the TabNavigator, for screens with multiple tabs, the Android equivalent of tabs, which you can toggle back and forth between.
1. Import components
import {TabNavigator} from ‘react-navigation’;
2. Start using it
You can set a separate title for each page, switch to the corresponding TAB to automatically switch the title, or you can use the previous page passed parameters as the title
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React from 'react'; import {Image,} from 'react-native'; import {TabNavigator} from 'react-navigation'; import HomePage from './app/home/HomePage'; import More from './app/more/More'; import MePage from './app/mepage/Me'; const App = TabNavigator({ HomePage: { screen: HomePage, navigationOptions: { tabBarLabel: TabBarVisible: true, // whether to hide the TAB bar. TabBarIcon: ({tintColor}) => (<Image style={{height: 30, resizeMode: 'contain', tintColor: tintColor}} source={require('./img/ic_launcher.png')}/>) }, }, More: { screen: More, navigationOptions: {// tabBarLabel: 'home ', tabBarVisible: true, // whether to hide the TAB bar. TabBarIcon: ({tintColor}) => (<Image style={{height: 30, resizeMode: 'contain', tintColor: tintColor}} source={require('./img/ic_launcher.png')}/>) }, }, MePage: { screen: MePage, navigationOptions: {// tabBarLabel: 'home ', tabBarVisible: true, // whether to hide the TAB bar. TabBarIcon: ({tintColor}) => (<Image style={{height: 30, resizeMode: 'contain', tintColor: tintColor}} source={require('./img/ic_launcher.png')}/>) }, }, }, { tabBarPosition: 'bottom', // sets the tabbar location. IOS defaults to the bottom and Android to the top. (Property values: 'top', 'bottom') swipeEnabled: true, // Whether to allow sliding between tabs animationEnabled: false, // Whether to show animations when changing tabs. Lazy: true, // Whether to render the TAB as needed, rather than making it in advance. This means to load the bottom TAB bar when the app is open. The default is false, but the recommended value is true. 'More', // set the default page component backBehavior: 'none', // press the back key to jump to the first Tab(home), none to not jump tabBarOptions: {activeTintColor: The foreground color of 'green',//label and icon is active (selected). ActiveBackgroundColor: 'red', //label and icon background color when active (selected). LabelStyle: {fontSize: 12}, //label style: {height: 50}, //tabbar style iconStyle: {height: 30} // Android,}}); export default App;Copy the code
const MyApp = TabNavigator({ Home: { screen: Home, navigationOptions: {// You can also write inside the component static navigationOptions tabBarLabel: 'home ', tabBarIcon: ({tintColor}) => (<Image source={require('./images/camera.png')} style={{tintColor: tintColor}}/>) } }, Notifications: {screen: Two, navigationOptions: {tabBarLabel: '2 pages ', tabBarIcon: ({tintColor}) => (<Image source={require('./images/add.png')} style={[{tintColor: tintColor}, styles.icon]}/>) } }, Me: {screen: Three, navigationOptions: {tabBarLabel: '3 pages ', tabBarIcon: ({tintColor}) => (<Image source={require('./images/more.png')} style={{tintColor: TintColor}}/>)}}}, {animationEnabled: false, tabBarPosition: SwipeEnabled: true, // Whether you can swipe left or right to switch TAB backBehavior: TabBarOptions: {activeTintColor: '#ff8500', inactiveTintColor: '#999', // Text and image unselected color showIcon: // Android does not display icon by default, you need to set true to show indicatorStyle: {// TabBar displays a line, you can set height to 0}, style: {backgroundColor: '# FFF ', // TabBar backgroundColor // height: 44}, labelStyle: {fontSize: 10, // text size},},});Copy the code
3. Common attributes
Take a look at the API
The API defined
TabNavigator(RouteConfigs, TabNavigatorConfig)
Copy the code
The first argument is RouteConfigs:
The RouteConfigs object maps from the route name to a route configuration and tells the navigation to render what the route is. See StackNavigator
The second parameter: TabNavigatorConfig
tabBarComponent
– The component to be used as a TAB bar, for example (this is the default on iOS), (this is the default on Android)TabBarBottom``TabBarTop
tabBarPosition
– The position of the TAB bar can be or'top'``'bottom'
swipeEnabled
– Whether to allow sliding between labelsanimationEnabled
– Whether to animate when changing labelslazy
– Whether to render labels lazily as needed instead of making them ahead of timetabBarOptions
– Configure the TAB bar, as shown below.
Several options are passed to the underlying router to modify the navigation logic:
initialRouteName
– routeName of the initial label route during the first loadorder
– Defines an array of routeNames for TAB orderpaths
– Map routeName to the path configuration, which overrides the path set in routeConfigs.backBehavior
– Does the back button switch the Tab key to the original Tab? If so, set to, otherwise. The default is behavior.initialRoute``none``initialRoute
tabBarOptions
For (default TAB bar on iOS)TabBarBottom
activeTintColor
– Label and icon colors for active tagsactiveBackgroundColor
– The background color of the active TABinactiveTintColor
– Label and icon colors for inactive labelsinactiveBackgroundColor
– Background color of inactive labelsshowLabel
– Whether to display the label of the label, default is truestyle
– Style object for the TAB barlabelStyle
– Style object for the TAB tagtabStyle
– Style object for the tag
Ex. :
tabBarOptions: {
activeTintColor: '#e91e63',
labelStyle: {
fontSize: 12,
},
style: {
backgroundColor: 'blue',
},
}
Copy the code
tabBarOptions
For (default TAB bar on Android)TabBarTop
activeTintColor
– Label and icon colors for active tagsinactiveTintColor
– Label and icon colors for inactive labelsshowIcon
– Whether to display the icon of the label. Default is falseshowLabel
– Whether to display the label of the label, default is trueupperCaseLabel
– Whether to capitalize labels. Default is truepressColor
– Color textures (Android> = 5.0)pressOpacity
– Press the opacity of the label (iOS and Android <5.0 only)scrollEnabled
– Whether to enable scrollable tabstabStyle
– Style object for the tagindicatorStyle
– Style object for label indicator (line at bottom of TAB)labelStyle
– Style object for the TAB tagiconStyle
– Style object for the label iconstyle
– Style object for the TAB bar
Ex. :
tabBarOptions: {
labelStyle: {
fontSize: 12,
},
tabStyle: {
width: 100,
},
style: {
backgroundColor: 'blue',
},
}
Copy the code
NavigationOptions:
title
The generic title can be used as alternate and headerTitle tabBarLabel
tabBarVisible
True or false Shows or hides the TAB bar, defaults to True if not set
tabBarIcon
React Element or a given function returns a React.Element to display {focused: Boolean, tintColor: string} in TAB
tabBarLabel
The title string of the label displayed in the label bar or React Element or the given function returns a React.Element to be displayed in the label bar. When not defined, use scenarios. To hide, see the previous section. { focused: boolean, tintColor: string }“title“tabBarOptions.showLabel
3. DrawerNavigator
/** * Created by Zhuoyuan on 2017/10/31. * [email protected] */ import React from 'React '; import { View, Text, StyleSheet, Button, Image } from 'react-native'; import {DrawerNavigator} from 'react-navigation'; Class Home extends react.ponent {static navigationOptions = {drawerLabel: 'Notifications Title ', drawerIcon: ({tintColor}) => ( <Image source={require('.. /.. /img/ic_launcher.png')} style={[styles.icon, {tintColor: tintColor}]} /> ), }; render() { const {navigate} = this.props.navigation; return ( <View style={styles.container}> <Text onPress={() => navigate('Home2', {name: </Text> <Text onPress={() => navigate('DrawerOpen')}> Open the cabinet </Text> </View>)}} class MyNotificationsScreen extends React.Component { static navigationOptions = { drawerLabel: <Image source={require('.. /.. /img/ic_launcher.png')} style={[styles.icon, {tintColor: tintColor}]} /> ), }; render() { return ( <Button onPress={() => this.props.navigation.goBack()} title="Go back home" /> ); } } const Drawer = DrawerNavigator({ Home: { screen: Home, navigationOptions:{drawerLabel:' handsome Home', headerTitle:' Home Title ', drawerIcon: ({tintColor}) => ( <Image source={require('.. /.. /img/ic_launcher.png')} style={[styles.icon, {tintColor: tintColor}]} /> ), } }, Notifications: { screen: MyNotificationsScreen, }, Notifications2: { screen: MyNotificationsScreen, }, }, { drawerWidth: 200, // Drawer width drawerPosition: 'left', // Options are left and right. Default is left // contentComponent:(navigation)=><Text>asa</Text>, contentOptions: {activeTintColor: '#e91e63', itemsContainerStyle: { marginVertical: 0, }, iconContainerStyle: { opacity: 1 }, } }); const styles = StyleSheet.create({ container: { marginTop: 22 }, icon: { width: 24, height: 24, }, }); export default Drawer;Copy the code
Used to easily set up screens with drawer navigation. For examples, see our exhibition demo.
class MyHomeScreen extends React.Component {
static navigationOptions = {
drawerLabel: 'Home',
drawerIcon: ({ tintColor }) => (
<Image
source={require('./chats-icon.png')}
style={[styles.icon, {tintColor: tintColor}]}
/>
),
};
render() {
return (
<Button
onPress={() => this.props.navigation.navigate('Notifications')}
title="Go to notifications"
/>
);
}
}
class MyNotificationsScreen extends React.Component {
static navigationOptions = {
drawerLabel: 'Notifications',
drawerIcon: ({ tintColor }) => (
<Image
source={require('./notif-icon.png')}
style={[styles.icon, {tintColor: tintColor}]}
/>
),
};
render() {
return (
<Button
onPress={() => this.props.navigation.goBack()}
title="Go back home"
/>
);
}
}
const styles = StyleSheet.create({
icon: {
width: 24,
height: 24,
},
});
const MyApp = DrawerNavigator({
Home: {
screen: MyHomeScreen,
},
Notifications: {
screen: MyNotificationsScreen,
},
});
Copy the code
Open and close drawers, navigate to and separate. ‘DrawerOpen’“’DrawerClose’
this.props.navigation.navigate('DrawerOpen'); // open drawer
this.props.navigation.navigate('DrawerClose'); // close drawer
Copy the code
The API defined
DrawerNavigator(RouteConfigs, DrawerNavigatorConfig)
Copy the code
RouteConfigs
The route CONFIGS object maps from the route name to a route configuration, which tells the navigation what to render the route. See example by. StackNavigator
DrawerNavigatorConfig
drawerWidth
– Width of drawerdrawerPosition
– The option is or. The default is location.left``right``left
contentComponent
– Components used to render drawer contents, such as navigation items. Receiving drawer pillar. By default. See below for more information.navigation``DrawerItems
contentOptions
– Configure drawer contents, see below.
Example:
The default is non-scrollable. To be scrollable, you must use this property to customize the container, as shown in the following example. DrawerView“View“contentComponent
{ drawerWidth: 200, drawerPosition: 'right', contentComponent: props => <ScrollView><DrawerItems {... props} /></ScrollView> }Copy the code
Several options are passed to the underlying router to modify the navigation logic:
initialRouteName
– routeName of the initial route.order
– An array of routeNames that defines the order of drawer items.paths
– Map routeName to the path configuration, which overrides the path set in routeConfigs.backBehavior
– Will the back button switch to the original route? If so, set to, otherwise. The default is behavior.initialRoute``none``initialRoute
Provide customizationcontentComponent
You can easily override the default component used: React-Navigation
import { DrawerItems } from 'react-navigation'; const CustomDrawerContentComponent = (props) => ( <View style={style.container}> <DrawerItems {... props} /> </View> ); const styles = StyleSheet.create({ container: { flex: 1, }, });Copy the code
contentOptions
forDrawerItems
items
– Route array, which can be modified or overriddenactiveItemKey
– The key marking the event routeactiveTintColor
– Label and icon colors for active tagsactiveBackgroundColor
– The background color of the active taginactiveTintColor
– Label and icon colors for invalid labelsinactiveBackgroundColor
– Background color of inactive labelsonItemPress(route)
– The function called when the item is pressedstyle
– Style object for the content sectionlabelStyle
– When your tag is a string, the style object overrides the style in the content sectionText
Example:
contentOptions: {
activeTintColor: '#e91e63',
style: {
marginVertical: 0,
}
}
Copy the code
Screen navigation options
title
The generic title can be used as an alternate and headerTitle drawerLabel
drawerLabel
String, React Element, or given function returns a React.Element, displayed in the drawer sidebar. When not sure, use {focused: Boolean, tintColor: string} ‘ ‘title
drawerIcon
React Element or a function that returns a React.Element displayed in the drawer sidebar {focused: Boolean, tintColor: string}
The navigation item
The navigator component created requires the following props: DrawerNavigator(…)
screenProps
– Pass additional options to children’s screens, such as:
const DrawerNav = DrawerNavigator({
// config
});
<DrawerNav
screenProps={/* this prop will get passed to the screen components and nav options as props.screenProps */}
/>
Copy the code
nested#DrawerNavigation
Keep in mind that if you nest DrawerNavigation, the drawer will appear below the parent navigation.
withNavigation
WithNavigation is a higher-order component that passes the navigation item to a wrapper component. This is useful when you cannot pass navigation items directly to a component, or when you do not want to pass navigation items in the case of deeply nested child nodes.
import React from 'react';
import { Button } from 'react-native';
import { withNavigation } from 'react-navigation';
class MyBackButton extends React.Component {
render() {
return <Button title="Back" onPress={() => { this.props.navigation.goBack() }} />;
}
}
// withNavigation returns a component that wraps MyBackButton and passes in the
// navigation prop
export default withNavigation(MyBackButton);
Copy the code