React-Native <navigator>:如何从实例化它的类中控制它

时间:2015-05-17 00:54:08

标签: react-native navigator

我在index.ios.js文件中实例化如下:

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

在同一个文件中,我有一个功能,我希望能够在导航器上触发操作,例如。

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

我如何实现这一目标?我以为我必须使用一些名为refs的东西,并尝试添加一个引用,如下所示:

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

然后用以下方法调用:     resetStack(){       // navigator.popToTop();       ref1.popToTop();     }

但这会导致错误: 找不到变量ref1

我如何实现这一目标?如何触发子组件中的方法?

2 个答案:

答案 0 :(得分:5)

对于有此问题的其他人。我对上面的代码非常接近,但忽略了将this.refs.referenceName添加到调用中,最终的代码是:

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

并将其称为:

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

答案 1 :(得分:-3)

使用路径和导航器上下文调用renderScene方法,允许您将导航器传递到场景组件中:

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

在ExampleScene中,您现在可以调用this.props.navigator.popToTop()

或者,从导航器中的组件调用Navigator.getContext(this)

Navigator.getContext(this).popToTop();

此处提供了文档:https://facebook.github.io/react-native/docs/navigator.html#navigation-context