【问题标题】:How do I access a Navigator component in the class it's created - React-Native如何在创建的类中访问 Navigator 组件 - React-Native
【发布时间】:2016-03-04 09:16:41
【问题描述】:

我是 React-Native 的新手,我正在尝试使用 组件的操作按钮和 组件的功能在我的应用程序中创建导航。我知道当您将组件推送到导航器堆栈时,您可以使用“this.props.navigator”访问该组件中的导航器。但是我不知道如何在声明它的类中访问导航器,我想在回调函数中调用 push 函数以执行 操作。

如果你看下面的代码 MyApp 类是我的应用程序的入口点,在渲染函数中它有一个包含 组件的主容器视图。我想访问 onActionSelected 函数中的导航器对象,但是 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>
    );
  }
}

【问题讨论】:

标签: android reactjs react-native


【解决方案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
    });   
  }
}

更多关于 refs 的信息here

【讨论】:

    猜你喜欢
    • 2018-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-17
    相关资源
    最近更新 更多