Avishay Bar
Avishay Bar

Reputation: 833

Access Class Method From Outside - React Native

I have the following class:

class Comp extends React.Component{
  onBack {
      navigator.pop();
  }
}

I want to able to access the class in the following function, which located in the main scope of my app but can't get it to work:

BackAndroid.addEventListener('hardwareBackPress', function() {
    Comp.onBack();
    return true;
});

Am I missing something here?

Upvotes: 1

Views: 1258

Answers (1)

oblador
oblador

Reputation: 3004

You need a reference to the Navigator instance, this can be done by using the ref prop or the following pattern from the official MoviesApp example:

var _navigator;
BackAndroid.addEventListener('hardwareBackPress', () => {
  if (_navigator && _navigator.getCurrentRoutes().length > 1) {
    _navigator.pop();
    return true;
  }
  return false;
});

var RouteMapper = function(route, navigationOperations, onComponentRef) {
  _navigator = navigationOperations;
  ...
};

var MoviesApp = React.createClass({
  render: function() {
    var initialRoute = {name: 'search'};
    return (
      <Navigator
        style={styles.container}
        initialRoute={initialRoute}
        configureScene={() => Navigator.SceneConfigs.FadeAndroid}
        renderScene={RouteMapper}
      />
    );
  }
});

Upvotes: 2

Related Questions