Moss Palmer
Moss Palmer

Reputation: 1854

React-Native <Navigator/> : How do I control it from the class that instantiated it

I have a instantiated in my index.ios.js file like this:

render() {
    return(
      <Navigator
        style={styles.navigator}
        renderScene={this.renderScene}
        initialRoute={{
          component: test,
          navigationBar: <NavigationBar title="home" />
        }}/>
    );
}

From this same file I have a function that I would like to be able to trigger an action on the navigator e.g.

resetStack(){
  // navigator.popToTop();
}

How do I achieve this? I thought I had to use something called refs and have tried adding a reference as follows:

render() {
    return(
      <Navigator
        ref="ref1"
        style={styles.navigator}
        renderScene={this.renderScene}
        initialRoute={{
          component: test,
          navigationBar: <NavigationBar title="home" />
        }}/>
    );
}

then calling this with: resetStack(){ // navigator.popToTop(); ref1.popToTop(); }

But this results in an error: Can't find variable ref1

How do I achieve this? How do I trigger methods in child components?

Upvotes: 4

Views: 3187

Answers (2)

Moss Palmer
Moss Palmer

Reputation: 1854

For anyone else with this issue. I was quite close with the above code but neglected to add the this.refs.referenceName to the call, the final code was:

render() {
    return(
      <Navigator
        ref="ref1"
        style={styles.navigator}
        renderScene={this.renderScene}
        initialRoute={{
          component: test,
          navigationBar: <NavigationBar title="home" />
        }}/>
    );
}

and call this with:

resetStack(){
  // navigator.popToTop();
  this.refs.ref1.popToTop();
}

Upvotes: 5

ide
ide

Reputation: 20808

The renderScene method is invoked with the route and the navigator context, which allows you to pass the navigator into the scene component:

renderScene(route, navigator) {
  return <ExampleScene navigator={navigator} />;
}

From within ExampleScene, you now can call this.props.navigator.popToTop().


Alternatively, call Navigator.getContext(this) from a component within a navigator:

Navigator.getContext(this).popToTop();

The documentation is available here: https://facebook.github.io/react-native/docs/navigator.html#navigation-context

Upvotes: -3

Related Questions