如何在其创建的类中访问Navigator组件 - React-Native

时间:2016-03-04 09:16:42

标签: android reactjs react-native

我是React-Native的新手,我正在尝试使用<的操作按钮在我的应用中创建导航。 ToolbarAndroid>具有<的功能的组件。导航>零件。我知道当您将组件推送到导航器堆栈时,您可以使用'this.props.navigator'访问该组件中的导航器。但是我无法弄清楚如何在声明它的类中访问导航器,我想在回调函数中调用push函数来获得< ToolbarAndroid>行动。

如果查看下面的代码,MyApp类是我的应用程序的入口点,在render函数中它有一个主容器视图,其中包含< ToolbarAndroid>和<导航>零件。我想访问onActionSelected函数中的navigator对象,但是this.props.navigator给了我一个未定义的错误。如何在onActionSelected回调中访问导航器?

我感觉可能是ES6导致了我的问题。

class MyApp extends Component {
  constructor(props) {
    super(props);
  }

  // I want to access navigator in this function
  onActionSelected(position) { 
  if (position === 0) { // index 
    this.props.navigator.push({
        name: 'FeedView',
        component: FeedView
      });   
    }
  }

  render() {
    return (
        <View style={styles.container}>
          <ToolbarAndroid 
          title="MyApp"
          style={styles.toolbar}
          actions={toolbarActions}
          onActionSelected={this.onPressFeed.bind(this)}
          navigator={this.props.navigator}>
          </ToolbarAndroid>

          <Navigator
                initialRoute={{name: 'WelcomeView', component: WelcomeView}}
                configureScene={() => {
                    return Navigator.SceneConfigs.FloatFromRight;
                }}
                renderScene={(route, navigator) => {
                    // count the number of func calls
                    console.log(route, navigator); 

                    if (route.component) {
                        return React.createElement(route.component, { navigator });
                    }
                }}
          />           
        </View>
    );
  }
}

1 个答案:

答案 0 :(得分:1)

您可以使用参考。

<Navigator
  ref='navigator'
  initialRoute={{name: 'WelcomeView', component: WelcomeView}}
  configureScene={() => {
    return Navigator.SceneConfigs.FloatFromRight;
  }}
  renderScene={(route, navigator) => {
    // count the number of func calls
    console.log(route, navigator); 
    if (route.component) {
      return React.createElement(route.component, { navigator });
    }
  }}
/> 

然后您可以使用以下命令在您的函数中访问它:

onActionSelected(position) { 
  if (position === 0) { // index 
    this.refs.navigator.push({
      name: 'FeedView',
      component: FeedView
    });   
  }
}

有关参考here的更多信息。