The article directories
-
- preface
- The overview
- StackNavigator navigation bar
-
- StackNavigatorConfig Navigator configuration
- NavigationOptions is the configuration option for the corresponding routing page
- Navigation Controls page hopping
- Page jump, pass value, callback pass parameter
- The callback parameter
- TabNavigator is the Tab Tab
-
- RouteConfigs Route configuration
- TabNavigatorConfig Tab configuration
- DrawerNavigator drawer navigation
-
- Extend the functionality
- Nested drawer navigation
- Develop reading
preface
During RN project development, it is common to see route jumps in the following form.
render() {
return (
<View>
<Text>2</Text>
<Button
title = "Jump to specified page"
onPress = {() => this.props.navigation.push('ChangePassword')}
/>
<Button
title = "Jump to specified page"
onPress = {() => this.props.navigation.navigate('Home')}
/>
<Button
title = "Return to previous page"
onPress = {() => this.props.navigation.goBack()}
/>
<Button
title = "Return to first page"
onPress = {() => this.props.navigation.popToTop()}
/>
</View>
)
}
Copy the code
In RN multi-page application development, page hopping is implemented by routing or navigator. Before version 0.44, developers were able to jump to and from the react Native app directly using the official Navigator component, but starting with version 0.44, Navigator was officially removed from the React Native core component library. Put it in the React-Native – Deprecated – custom-Components module.
To continue using Navigator, run the yarn add react-native-deprecated-custom-components command before using it. This is not recommended, however, and developers are advised to use the React-Navigation library directly. React Navigation is a well-known page navigation library in react Native community, which can be used for various page jump operations.
In this article, WE will learn about related skills and knowledge based on RN’s official recommended Route navigation component, React navigation.
The overview
In React Native, it is officially recommended to use React navigation to jump between different interfaces and switch between different sections. React-navigation is said to have a native-like performance experience. It could become the mainstay of future React Native navigation components.
Currently, React navigation supports three types of navigators: StackNavigator, TabNavigator, and DrawerNavigator. The specific differences are as follows:
1. StackNavigator: Similar to normal Navigator, the navigation bar at the top of the screen is used to jump between different pages. 2. TabNavigator: equivalent to TabBarController in iOS, the TAB bar at the bottom of the screen is mainly used for switching between different interfaces on the same page; 3, DrawerNavigator: drawer effect, side slide out;
StackNavigator navigation bar
StackNavigator(RouteConfigs, StackNavigatorConfig)
Copy the code
The StackNavigator component uses stack-like page navigation to jump from interface to interface. If you want to use StackNavigator, be sure to sign up for navigation first.
CreateStackNavigator is used to configure the stack management page. In createStackNavigator mode, to facilitate unified page management, create a RouterConfig.js file and register the page with createStackNavigator. InitialRouteName is also used to declare the initial page of the application. Also, the navigator stack needs to be wrapped using the createAppContainer function. Example code is as follows:
RouterConfig.js
file
import {createAppContainer,createStackNavigator} from 'react-navigation';
import MainPage from './MainPage'
import DetailPage from "./DetailPage";
const AppNavigator = createStackNavigator({
MainPage: MainPage,
DetailPage:DetailPage
},{
initialRouteName: "MainPage",});export default createAppContainer(AppNavigator);
Copy the code
Next, import the StacknavigatorPage.js file as a component in the entry file. Such as:
import StackNavigatorPage from './src/StackNavigatorPage'
export default class App extends Component<Props> {
render() {
return( <StackNavigatorPage/> ); }}Copy the code
From there, you can configure navigation.
const Navigator = StackNavigator(
{
Tab: { screen: Tab },
Web: { screen: WebScene },
GroupPurchase: { screen: GroupPurchaseScene },
},
{
navigationOptions: {
// headerStyle: { backgroundColor: color.theme }
headerBackTitle: null,
headerTintColor: '# 333333',
showIcon: true,}});Copy the code
There are three interfaces configured for the navigator, and more can be added later if needed. There is a Tab interface for switching between the main interface and two other interfaces for displaying data.
StackNavigatorConfig Navigator configuration
InitialRouteName – The route name of the initial displayed page in the navigator component. If this is not set, the first route page is the initial displayed page by default.
InitialRouteParams – give the parameters of the initial route, in the initial page can through this. Props. Navigation. State. The params to obtain;
NavigationOptions – Configuration options for the routing page, overridden by navigationOptions in RouteConfigs.
Paths-mapping configuration for path coverage set in routing;
Mode – Indicates the page skipping mode, including card and modal. The default mode is card:
card
– Native system default jump, left and right interchange;modal
– Only for iOS platform, modal jump, up and down switch;HeaderMode – The animation mode of the head when a page jumps, including float, Screen, and None:
float
– Gradient, similariOS
The original effect, no transparency;screen
– The title fades in and out with the screen, just like wechat;none
– No animation;CardStyle – Sets a uniform style for each page, such as background color, font size, etc.
TransitionConfig – Configures the animation of the page jump, overriding the default animation effect;
OnTransitionStart – called when the page jump animation is about to start;
OnTransitionEnd – called as soon as the page jump animation completes;
Code examples:
const StackNavigatorConfig = {
initialRouteName: 'Home',
initialRouteParams: {initPara: 'Initial page Parameters'},
navigationOptions: {
title: 'title',
headerTitleStyle: {fontSize: 18, color: '# 666666'},
headerStyle: {height: 48, backgroundColor: The '#'},
},
paths: 'page/main',
mode: 'card',
headerMode: 'screen',
cardStyle: {backgroundColor: "#ffffff"},
transitionConfig: (() => ({
screenInterpolator: CardStackStyleInterpolator.forHorizontal,
})),
onTransitionStart: (() => {
console.log('Page jump animation starts');
}),
onTransitionEnd: (() => {
console.log('End of page jump animation'); })};Copy the code
NavigationOptions is the configuration option for the corresponding routing page
title
– Can be used as a header headerheaderTitle
Or,Tab
The titletabBarLabel
;header
– User-defined header component. After this attribute is used, the header component of the system disappears. If you want to customize it on the page, you can set this parameter tonull
, so you don’t have a page with a height of 64 navigationBar;headerTitle
– The header title, that is, the page titleheaderBackTitle
– Returns the title, default istitle
;headerTruncatedBackTitle
– Returns the title when the title cannot be displayed (for example, the return title is too long). Default is”Back
“;headerRight
– Head right component;headerLeft
– Head left component;headerStyle
-Header component style;headerTitleStyle
-Header header style;headerBackTitleStyle
– Header returns the style of the title;headerTintColor
– Head colorHeaderPressColorAndroid - Android 5.0
The aboveMD
Style of ripple color;gesturesEnabled
– No sideslip return,iOS
The defaulttrue
,Android
The defaultfalse
;
Use the sample
// Register the navigation
const Navs = StackNavigator({
Home: { screen: Tabs },
HomeTwo: {
screen: HomeTwo, // All else is necessary
path:'app/homeTwo'.// Use url navigation, such as Web app and Deep Linking
navigationOptions: {} // This overrides the static navigationOptions setting in the component. See below for specific parameters;
},
HomeThree: { screen: HomeThree },
HomeFour: { screen: HomeFour }
}, {
initialRouteName: 'Home'.// Displays the interface by default
navigationOptions: { // The default option for screen navigation. You can also set static navigationOptions in the component (which overrides the Settings here).
header: { // Navigation bar related Settings
backTitle: 'return'.// top left corner returns key text
style: {
backgroundColor: '#fff'
},
titleStyle: {
color: 'green'
}
},
cardStack: {
gesturesEnabled: true
}
},
mode: 'card'.// Page switch mode, left and right card(iOS equivalent to push), up and down modal(iOS equivalent to modal)
headerMode: 'screen'.// Display mode of the navigation bar, screen: gradient transparency, float: no transparency, None: hidden navigation bar
onTransitionStart: ()=>{ console.log('Navigation bar switch begins'); }, / / callback
onTransitionEnd: ()=>{ console.log('End of navigation bar switch'); } / / callback
});
Copy the code
NavigationOptions can also be configured statically in the corresponding page.
// Configure page navigation options
static navigationOptions = ({navigation}) => ({
title: 'HOME',
titleStyle: {color: '#ff00ff'},
headerStyle:{backgroundColor:'# 000000'}}); render() {return (
<View></View>
)
};
}
Copy the code
Statically configure the properties in navigationOptions on the page, Overrides the corresponding properties in navigationOptions of the RouteConfigs and StackNavigatorConfig parameters in the StackNavigator constructor.
NavigationOptions attributes have the following priority:
Static Configuration > RouteConfigs > StackNavigatorConfig
At this point, we can use the configuration directly in the component, or we can use it as mentioned at the beginning of this article:
const Navigator = StackNavigator(RouteConfigs, StackNavigatorConfig);
export default class Main extends Component {
render() {
return (
<Navigator/>
)
};
}
Copy the code
At this point, we have configured the navigator and the corresponding routing page, but we also need navigation to jump to the page.
Navigation Controls page hopping
On each page in the navigator, there is a navigation property, which has the following properties/methods, which can be viewed in the component console.log(this.props).
navigate
– Jump to other pages;state
– Current page navigator status;setParams
– Change route parameters;goBack
– return;dispatch
– Send oneaction
;
navigate
this. Props. Navigation. Navigate (" Two ", {name: "Two"})// push next page
Copy the code
routeName
: Indicates the registered destination route name.params
: Pass parameters to the next interface;action
: If the interface is anavigator
So, this is going to runsub-action
;
State state contains parameters params, key, and routeName routeName.
routeName
: Route name;key
: Route id;params
: parameters;
SetParams enclosing props. Navigation. SetParams allowed to change the parameters of the router interface, this method can be used to dynamically change the contents of the navigation bar. Such as buttons or titles that can be used to update headers.
GoBack returns to the previous page and can pass no arguments, arguments, or null.
this.props.navigation.goBack(); // Go back to the previous page
this.props.navigation.goBack(null); // Go back to any page
this.props.navigation.goBack('Home'); // Go back to the Home page
Copy the code
dispatch
this.props.navigation.dispatch
Copy the code
You can dispatch some actions. The main supported actions are:
1. Navigate
import { NavigationActions } from 'react-navigation'
const navigationAction = NavigationActions.navigate({
routeName: 'Profile',
params: {},
// navigate can have a nested navigate action that will be run inside the child router
action: NavigationActions.navigate({ routeName: 'SubProfileRoute'})})this.props.navigation.dispatch(navigationAction)
Copy the code
2. The Reset Reset method clears the original route record and adds the new route information. You can specify multiple actions and index to specify the route page displayed by default.
import { NavigationActions } from 'react-navigation'
const resetAction = NavigationActions.reset({
index: 0,
actions: [
NavigationActions.navigate({ routeName: 'Profile'}),
NavigationActions.navigate({ routeName: 'Two'})]})this.props.navigation.dispatch(resetAction)
Copy the code
SetParams updates the parameter for the specified router. The parameter must already exist in the param of the router.
import { NavigationActions } from 'react-navigation'
const setParamsAction = NavigationActions.setParams({
params: {}, // these are the new params that will be merged into the existing route params
// The key of the route that should get the new params
key: 'screen-123',})this.props.navigation.dispatch(setParamsAction)
Copy the code
Page jump, pass value, callback pass parameter
Jump, pass the value
const {navigate} = this.props.navigation;
<TouchableHighlight onPress={()=>{
navigate('PlanDetail',{name:'leslie',id:100}); }} >Copy the code
// return to the previous page
this.props.navigation.goBack();
Copy the code
The next interface receive parameters through this. Props. Navigation. State. Params receiving parameters
export default class Home1 extends Component {
static navigationOptions = {
// Title can be set as a function, and state is passed in automatically
title: ({state}) => `${state.params.name}`,
};
componentDidMount() {
const {params} = this.props.navigation.state;
constid = params.id; }}Copy the code
The callback parameter
The current interface is switched to
navigate('Detail', {// Jump to the next page with a parameter
callback: (data)=>{
console.log(data); // Print the value as: 'callback parameter'}});Copy the code
The next screen is preloaded before returning
const {navigate,goBack,state} = this.props.navigation;
// On the second page, before goBack, fetch the method from the previous page and pass back the argument, which resets the Render method
state.params.callback('Callback parameters');
goBack();
Copy the code
TabNavigator is the Tab Tab
TabNavigator(RouteConfigs, TabNavigatorConfig)
Copy the code
API is similar to StackNavigator, the RouteConfigs parameter is the routing configuration and the TabNavigatorConfig parameter is the Tab Tab configuration.
To switch bottom tabs, you can directly use the createBottomTabNavigator interface provided by The React navigation, and the navigator needs to be wrapped with the createAppContainer function before it can be called as a React component. Such as:
import React, {PureComponent} from 'react';
import {StyleSheet, Image} from 'react-native';
import {createAppContainer, createBottomTabNavigator} from 'react-navigation'
import Home from './tab/HomePage'
import Mine from './tab/MinePage'
const BottomTabNavigator = createBottomTabNavigator(
{
Home: {
screen: Home,
navigationOptions: () => ({
tabBarLabel: 'home',
tabBarIcon:({focused})=>{
if(focused){
return(
<Image/> // The selected image)}else{
return(
<Image/> // Default image
)
}
}
}),
},
Mine: {
screen: Mine,
navigationOptions: () => ({
tabBarLabel: 'I', tabBarIcon: {focused}) = > {... }})}}, {// Default parameter Settings
initialRouteName: 'Home',
tabBarPosition: 'bottom',
showIcon: true,
showLabel: true,
pressOpacity: 0.8,
tabBarOptions: {
activeTintColor: 'green',
style: {
backgroundColor: '#fff',},}});const AppContainer = createAppContainer(BottomTabNavigator);
export default class TabBottomNavigatorPage extends PureComponent {
render() {
return( <AppContainer/> ); }}Copy the code
RouteConfigs Route configuration
Route configuration is the same as StackNavigator. Configure the route and the corresponding screen page. NavigationOptions is the configuration options of the corresponding routing page.
title
–Tab
Title, can be used asheaderTitle
和tabBarLabel
Back the title;tabBarVisible
–Tab
Visible or not. Default value if not settrue
;tabBarIcon
–Tab
theicon
Components can be based on{focused:boolean, tintColor: string}
Method to return aicon
Components;tabBarLabel
–Tab
The title string or component that is displayed in the{ focused: boolean, tintColor: string }
; Method returns a component;
Code examples:
Mine: {
screen: MineScene,
navigationOptions: ({ navigation }) => ({
tabBarLabel: 'I',
tabBarIcon: ({ focused, tintColor }) => (
<TabBarItem
tintColor={tintColor}
focused={focused}
normalImage={require('./img/tabbar/[email protected]')}
selectedImage={require('./img/tabbar/[email protected]'} />)}),},Copy the code
TabBarItem
Custom Components
class TabBarItem extends PureComponent {
render() {
let selectedImage = this.props.selectedImage ? this.props.selectedImage : this.props.normalImage
return (
<Image
source={this.props.focused
? selectedImage
: this.props.normalImage}
style={{ tintColor: this.props.tintColor, width: 25, height: 25 }}
/>
); }}Copy the code
TabNavigatorConfig Tab configuration
-
Tabbarcomponent-tab component with TabBarBottom and TabBarTop values, which default to TabBarBottom on iOS and TabBarTop on Android.
TabBarTop
– At the top of the page;TabBarBottom
– At the bottom of the page;
-
TabBarPosition – The position of the Tab Tab, either top or bottom
top
Above:bottom
Below:
-
SwipeEnabled – Whether you can swipe to switch between Tab tabs;
-
AnimationEnabled – Click the Tab Tab to toggle whether the interface needs animation;
-
Lazy – Whether a page is lazy to load;
-
InitialRouteName – The name of the page route corresponding to the Tab initially displayed;
-
Order – Represents the order of Tab tabs with an array of route names. Default is route configuration order;
-
Paths-path configuration;
-
BackBehavior – The processing of android when the return key is hit, with two values initialRoute and None:
initailRoute
– Return to the initial interface;none
– exit;
-
TabBarOptions -tab configuration properties, TabBarTop and TabBarBottom properties are inconsistent:
When used with TabBarTop:
activeTintColor
– Selected text color;inactiveTintColor
– Unselected text color;showIcon
– Whether to display ICONS by default.showLabel
– Whether to display labels, default display;upperCaseLabel
– Whether to use uppercase letters. The default value is uppercase letters.pressColor
–The android 5.0
Above MD style ripple color;pressOpacity
–android5.0
The following oriOS
Pressed transparency;scrollEnabled
– Whether scrolling is possible;tabStyle
– Single Tab style;indicatorStyle
-Indicator style;labelStyle
– Label style;iconStyle
–icon
The style;style
– Entire TabBar style;
When used with TabBarBottom:
activeTintColor
– Select Tab text color;inactiveTintColor
– Unselected Tab text color;activeBackgroundColor
– Select the Tab background color;inactiveBackgroundColor
– Unselected Tab background color;showLabel
– Whether to display the title, the default display;style
– Entire TabBar style;labelStyle
– Label style;tabStyle
– Single Tab style;
Use the bottom TAB:
import React, {Component} from 'react';
import {StackNavigator, TabBarBottom, TabNavigator} from "react-navigation";
import HomeScreen from "./index18/HomeScreen";
import NearByScreen from "./index18/NearByScreen";
import MineScreen from "./index18/MineScreen";
import TabBarItem from "./index18/TabBarItem";
export default class MainComponent extends Component {
render() {
return( <Navigator/> ); }}const TabRouteConfigs = {
Home: {
screen: HomeScreen,
navigationOptions: ({navigation}) => ({
tabBarLabel: 'home',
tabBarIcon: ({focused, tintColor}) => (
<TabBarItem
tintColor={tintColor}
focused={focused}
normalImage={require('./img/tabbar/pfb_tabbar_homepage_2x.png')}
selectedImage={require('./img/tabbar/pfb_tabbar_homepage_selected_2x.png')}
/>
),
}),
},
NearBy: {
screen: NearByScreen,
navigationOptions: {
tabBarLabel: 'near',
tabBarIcon: ({focused, tintColor}) => (
<TabBarItem
tintColor={tintColor}
focused={focused}
normalImage={require('./img/tabbar/pfb_tabbar_merchant_2x.png')}
selectedImage={require('./img/tabbar/pfb_tabbar_merchant_selected_2x.png')}
/>
),
},
}
,
Mine: {
screen: MineScreen,
navigationOptions: {
tabBarLabel: 'I',
tabBarIcon: ({focused, tintColor}) => (
<TabBarItem
tintColor={tintColor}
focused={focused}
normalImage={require('./img/tabbar/pfb_tabbar_mine_2x.png')}
selectedImage={require('./img/tabbar/pfb_tabbar_mine_selected_2x.png')} />),},}};const TabNavigatorConfigs = {
initialRouteName: 'Home',
tabBarComponent: TabBarBottom,
tabBarPosition: 'bottom',
lazy: true};const Tab = TabNavigator(TabRouteConfigs, TabNavigatorConfigs);
const StackRouteConfigs = {
Tab: {
screen: Tab,
}
};
const StackNavigatorConfigs = {
initialRouteName: 'Tab',
navigationOptions: {
title: 'title',
headerStyle: {backgroundColor: '#5da8ff'},
headerTitleStyle: {color: '# 333333'}}};const Navigator = StackNavigator(StackRouteConfigs, StackNavigatorConfigs);
Copy the code
Use the top TAB:
import React, {Component} from "react";
import {StackNavigator, TabBarTop, TabNavigator} from "react-navigation";
import HomeScreen from "./index18/HomeScreen";
import NearByScreen from "./index18/NearByScreen";
import MineScreen from "./index18/MineScreen";
export default class MainComponent extends Component {
render() {
return( <Navigator/> ); }}const TabRouteConfigs = {
Home: {
screen: HomeScreen,
navigationOptions: ({navigation}) => ({
tabBarLabel: 'home',
}),
},
NearBy: {
screen: NearByScreen,
navigationOptions: {
tabBarLabel: 'near',
},
}
,
Mine: {
screen: MineScreen,
navigationOptions: {
tabBarLabel: 'I',}}};const TabNavigatorConfigs = {
initialRouteName: 'Home',
tabBarComponent: TabBarTop,
tabBarPosition: 'top',
lazy: true,
tabBarOptions: {}
};
const Tab = TabNavigator(TabRouteConfigs, TabNavigatorConfigs);
const StackRouteConfigs = {
Tab: {
screen: Tab,
}
};
const StackNavigatorConfigs = {
initialRouteName: 'Tab',
navigationOptions: {
title: 'title',
headerStyle: {backgroundColor: '#5da8ff'},
headerTitleStyle: {color: '# 333333'}}};const Navigator = StackNavigator(StackRouteConfigs, StackNavigatorConfigs);
Copy the code
, of course, in addition to supporting create TAB at the bottom, the react – navigation also supports creating TAB at the top at this time only need to use the react – createMaterialTopTabNavigator can be provided by the navigation. If you want to use the drawer-like menu function, you can also use the createDrawerNavigator provided by React – Navigation.
DrawerNavigator drawer navigation
Some apps will use the side slide drawer to realize the navigation of the main page. DrawerNavigator can easily realize the navigation of the drawer in RN.
DrawerNavigator(RouteConfigs, DrawerNavigatorConfig)
Copy the code
As with the TabNavigator constructor, the parameter configuration is similar.
RouteConfigs drawer navigation route configuration RouteConfigs, exactly the same as the routing configuration and TabNavigator, screen corresponding routing configuration page, navigationOptions drawer of the corresponding page configuration:
title
– Drawer titles, andheaderTitle
、drawerLabel
The same;drawerLabel
– Tag string, or custom component, can be based on{ focused: boolean, tintColor: string }
Function to return a custom component as a label;drawerIcon
Drawer –icon
, can be based on{ focused: boolean,tintColor: string }
Function to return a custom component asicon
;
DrawerNavigatorConfig
The configuration properties
DrawerWidth – drawerWidth. You can use Dimensions to obtain screen width for dynamic calculation. DrawerPosition – drawerPosition, can be left or right;
ContentComponent – Drawer contents component that allows you to customize the contents of the drawer by sliding it sideways. Default is DrawerItems;
ContentOptions – Properties used to configure the contents of the drawer. When used to configure DrawerItems is the configuration property option:
items
– Array of route names for drawer columns, which can be modified;activeItemKey
– Of the currently selected pagekey id
;activeTintColor
– Select the text color of the item state;activeBackgroundColor
– Select the background color of the item;inactiveTintColor
– Text color of unselected item status;inactiveBackgroundColor
– Background color of the unselected itemonItemPress(route)
– This method is called when an item is pressed;Style – the style of the contents of the drawer; LabelStyle – drawer entry title/labelStyle;
InitialRouteName – Initializes the displayed page route name;
Order – drawer navigation column order, represented by an array of route names;
Paths;
BackBehavior – The processing of android when the return key is hit, with two values initialRoute and None:
- InitailRoute: returns to the initial interface.
- None: quit
Example drawer navigation:
import React, {Component} from 'react';
import {DrawerNavigator, StackNavigator, TabBarBottom, TabNavigator} from "react-navigation";
import HomeScreen from "./index18/HomeScreen";
import NearByScreen from "./index18/NearByScreen";
import MineScreen from "./index18/MineScreen";
import TabBarItem from "./index18/TabBarItem";
export default class MainComponent extends Component {
render() {
return( <Navigator/> ); }}const DrawerRouteConfigs = {
Home: {
screen: HomeScreen,
navigationOptions: ({navigation}) => ({
drawerLabel : 'home',
drawerIcon : ({focused, tintColor}) => (
<TabBarItem
tintColor={tintColor}
focused={focused}
normalImage={require('./img/tabbar/pfb_tabbar_homepage_2x.png')}
selectedImage={require('./img/tabbar/pfb_tabbar_homepage_selected_2x.png')}
/>
),
}),
},
NearBy: {
screen: NearByScreen,
navigationOptions: {
drawerLabel : 'near',
drawerIcon : ({focused, tintColor}) => (
<TabBarItem
tintColor={tintColor}
focused={focused}
normalImage={require('./img/tabbar/pfb_tabbar_merchant_2x.png')}
selectedImage={require('./img/tabbar/pfb_tabbar_merchant_selected_2x.png')}
/>
),
},
},
Mine: {
screen: MineScreen,
navigationOptions: {
drawerLabel : 'I',
drawerIcon : ({focused, tintColor}) => (
<TabBarItem
tintColor={tintColor}
focused={focused}
normalImage={require('./img/tabbar/pfb_tabbar_mine_2x.png')}
selectedImage={require('./img/tabbar/pfb_tabbar_mine_selected_2x.png')} />),},}};const DrawerNavigatorConfigs = {
initialRouteName: 'Home',
tabBarComponent: TabBarBottom,
tabBarPosition: 'bottom',
lazy: true,
tabBarOptions: {}
};
const Drawer = DrawerNavigator(DrawerRouteConfigs, DrawerNavigatorConfigs);
const StackRouteConfigs = {
Drawer: {
screen: Drawer,
}
};
const StackNavigatorConfigs = {
initialRouteName: 'Drawer',
navigationOptions: {
title: 'title',
headerStyle: {backgroundColor: '#5da8ff'},
headerTitleStyle: {color: '# 333333'}}};const Navigator = StackNavigator(StackRouteConfigs, StackNavigatorConfigs);
Copy the code
Extend the functionality
Default DrawerView is not scrollable. To implement scrollable views, you must use a custom container called contentComponent:
{drawerWidth:200ContentComponent: props => <ScrollView> <DrawerItems {... props}></DrawerItems> </ ScrollView> }Copy the code
You can override the default navigation components and use DrawerItems to customize the navigation components:
import {DrawerItems} from 'react-navigation';
const CustomDrawerContentComponent = (props) => (
<View style = {style.container}>
<DrawerItems {... props} />
</View>
);
Copy the code
Nested drawer navigation
If a DrawerNavigation is nested, the drawer will appear below the parent navigation.
In the test of the top navigation bar title of the custom React-Navigation adaptation, it was found that the title of the title bar was centered on iPhone, but left aligned on Android. So need to modify the source code, adaptation. Node_modules — react-navigation — SRC — views — header. js
title: {
bottom: 0,
left: TITLE_OFFSET,
right: TITLE_OFFSET,
top: 0,
position: 'absolute',
alignItems: 'center',}Copy the code
The above method by modifying the source code is actually a slight disadvantage, after all, the scalability is not good. There is another way to do this: set headerTitleStyle alignSelf to ‘Center’ in navigationOptions. Remove return key text display
Node_modules — react-navigation — SRC — views — headerbackbutton.js — node_modules — react-navigation — SRC — views — headerbackbutton.js
{
Platform.OS === 'ios' &&
title &&
<Text
onLayout={this._onTextLayout}
style={[styles.title, { color: tintColor }]}
numberOfLines={1}
>
{backButtonTitle}
</Text>
}
Copy the code
When setting the left and right buttons in the header, you can’t avoid setting the button click event, but there is a problem. NavigationOptions is set to static. So you can’t call the Component method directly through this in the button’s onPress method. How to solve it?
In the official documentation, the author presents the idea of setting params to dynamically set the header headings. You can pass the callback argument to Params using navigation in navigationOption and set it to onPress:
componentDidMount () {
/** * passes the click callback function */ as an argument
this.props.navigation.setParams({
switch: () = >this.switchView()
});
}
/** * Switch views */
switchView() {
alert('switch')}static navigationOptions = ({navigation,screenProps}) => ({
headerTitle: 'Enterprise Services',
headerTitleStyle: CommonStyles.headerTitleStyle,
headerRight: (
<NavigatorItem icon={ Images.ic_navigator } onPress={ ()=> navigation.state.params.switch() }/>
),
headerStyle: CommonStyles.headerStyle
});
Copy the code
It is common to see the need to use BackHandler to handle the effect of returning and exiting the App twice by clicking the back button. I believe that many people implementing this function under react-Navigation have encountered many problems, for example, other screens cannot return. That is, the phone itself returns events that are intercepted before react-Navigation. How do I incorporate my react-natigation implementation? There are two ways to do this:
(1) In the StackNavigator register interface, register BackHandler
componentWillMount(){
BackHandler.addEventListener('hardwareBackPress'.this._onBackAndroid );
}
componentUnWillMount(){
BackHandler.addEventListener('hardwareBackPress'.this._onBackAndroid);
}
_onBackAndroid=()=>{
let now = new Date().getTime();
if(now - lastBackPressed < 2500) {
return false;
}
lastBackPressed = now;
ToastAndroid.show('Click exit app again',ToastAndroid.SHORT);
return true;
}
Copy the code
(2) Listen on the Router in the react navigation
/** * handle android return key */
const defaultStateAction = AppNavigator.router.getStateForAction;
AppNavigator.router.getStateForAction = (action,state) => {
if(state && action.type === NavigationActions.BACK && state.routes.length === 1) {
if (lastBackPressed + 2000 < Date.now()) {
ToastAndroid.show(Constant.hint_exit,ToastAndroid.SHORT);
lastBackPressed = Date.now();
const routes = [...state.routes];
return{... state, ... state.routes, index: routes.length -1}; }}return defaultStateAction(action,state);
};
Copy the code
In Android, the default animation for navigation is up and down. How to switch left and right? Very simple configuration:
import CardStackStyleInterpolator from 'react-navigation/src/views/CardStackStyleInterpolator';
Copy the code
Then add the following code under the StackNavigator configuration:
transitionConfig:()=>({
screenInterpolator: CardStackStyleInterpolator.forHorizontal,
})
Copy the code
When we quickly click the jump, will open a number of repeated interface, how to solve the problem? Git Git Git Git Git Git Git Git Git Git
Find the addNavigationhelpers. js file in the SCR folder and replace it with the following text:
export default function<S: *>(navigation: NavigationProp<S, NavigationAction>) {
// Add click judgment
let debounce = true;
return{... navigation, goBack: (key? :? string):boolean=> navigation.dispatch( NavigationActions.back({ key: key === undefined ? navigation.state.key : key, }), ), navigate: (routeName: string, params? : NavigationParams, action? : NavigationAction,):boolean= > {if (debounce) {
debounce = false;
navigation.dispatch(
NavigationActions.navigate({
routeName,
params,
action,
}),
);
setTimeout(
() => {
debounce = true;
},
500,);return true;
}
return false;
},
/** * For updating current route params. For example the nav bar title and * buttons are based on the route params. * This means `setParams` can be used to update nav bar for example. */
setParams: (params: NavigationParams): boolean =>
navigation.dispatch(
NavigationActions.setParams({
params,
key: navigation.state.key,
}),
),
};
}
Copy the code
Develop reading
- The react – navigation website
- “ReactNative advanced (27) : createMaterialTopTabNavigator top navigation components”