diff --git a/README.md b/README.md index 2cc0154..58c19ae 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,6 @@ const firstRoute = { class MyApp extends React.Component { render() { - return ( `** object used to initialize the navigation can take the follo - `rightCorner`: If you have the same occuring action buttons on the right side of your navigation bar (like the Twitter "Compose"-button), you can specify a component for that view. - `customAction`: A special callback prop for your action buttons (this can be handy for triggering a side menu for example). The action gets triggered from your custom `leftCorner` or `rightCorner` components by calling `this.props.customAction("someActionName")` from them. It is then picked up like this: ``. - `hideNavigationBar`: Hide the navigation bar, always +- `handleBackAndroid` (Boolean value): Apply a listener to the native back button on Android. On click, it will go to the previous route until it reach the first scene, then it will exit the app. The **`this.props.toRoute()`** callback prop takes one parameter (a JavaScript object) which can have the following keys: - `name`: The name of your route, which will be shown as the title of the navigation bar unless it is changed. diff --git a/components/NavBarContainer.js b/components/NavBarContainer.js index e05d573..f37ff72 100644 --- a/components/NavBarContainer.js +++ b/components/NavBarContainer.js @@ -1,4 +1,4 @@ -import React, { StyleSheet, View, PropTypes } from 'react-native'; +import React, { StyleSheet, View, PropTypes, Platform, BackAndroid } from 'react-native'; import NavBarContent from './NavBarContent'; @@ -8,6 +8,7 @@ const propTypes = { borderColor: PropTypes.string, currentRoute: PropTypes.object.isRequired, customAction: PropTypes.func, + handleBackAndroid: PropTypes.bool, leftProps: PropTypes.object, navigator: PropTypes.object.isRequired, rightCorner: PropTypes.func, @@ -50,6 +51,19 @@ class NavBarContainer extends React.Component { }); } + componentDidMount() { + if (Platform.OS === 'android' && !!this.props.handleBackAndroid) { + BackAndroid.addEventListener('hardwareBackPress', () => { + if (this.props.currentRoute.index > 0) { + this.goBack(); + return true; + } + + return false; + }); + } + } + componentWillReceiveProps(newProps) { if (this.props && this.props.currentRoute.index !== newProps.currentRoute.index) { this.setState({ @@ -58,6 +72,12 @@ class NavBarContainer extends React.Component { } } + componentWillUnmount() { + if (Platform.OS === 'android' && !!this.props.handleBackAndroid) { + BackAndroid.removeEventListener('hardwareBackPress'); + } + } + goBack() { this.props.toBack(this.props.navigator); } diff --git a/index.js b/index.js index e38d00d..c28692b 100644 --- a/index.js +++ b/index.js @@ -207,6 +207,7 @@ class Router extends React.Component { rightProps={this.state.rightProps} titleProps={this.state.titleProps} customAction={this.customAction} + handleBackAndroid={this.props.handleBackAndroid} /> ); }