在本机组件之间导航

时间:2018-08-15 19:34:38

标签: javascript reactjs react-native react-router react-navigation

我需要在React Native的两个视图之间导航。但是问题出在我的组件上,要浏览的按钮在另一个组件上。我使用反应导航。

让我告诉你:

我的组件MainPage在这里

class MainPage extends Component {
  render() {
    return <View style={styles.container}>
              <ComponentWithButton /> 
          </View>
  }
}

所以在我的组件ComponentWithButton中:

class ComponentWithButton extends Component {
      goToComponent(){
         this.props.navigation.push('Next')
      }
      render() {
        return <View style={styles.container}>
                  <Button onPress={this.goToComponent.bind(this)}/> 
              </View>
      }
    }

我的下一个组件称为NextComponent

我有未定义的错误不是对象(正在评估“ this.props.navigation.push”)

我的堆栈导航器是这样:

const RootStack = StackNavigator(
  {
    Main: {
      screen: MainPage
    },
    Next: {
      screen: NextComponent
    }
  },
  {
    initialRouteName: "Main"
  },
  {
    navigationOptions: {
      header: { visible: false }
    }
  }
);

我尝试只用一个组件来运行我的代码,它运行良好。我认为这是有问题的,因为ComponentWithButton没有在我的RootStack中被调用或类似的东西。我不知道我是新手

2 个答案:

答案 0 :(得分:2)

您没有将导航道具传递给 <ComponentWithButton />

做这样的事情

<ComponentWithButton navigation={this.props.navigation}/>

方法也应该是

this.props.navigation.navigate('Next')

如果我记得

答案 1 :(得分:2)

react-navigation具有一个带有Navigation的功能,该功能可在您的任何组件中填充导航道具。就是这样使用它:

import { withNavigation } from 'react-navigation';

class ComponentWithButton extends Component {
      goToComponent(){
         this.props.navigation.push('Next')
      }
      render() {
        return <View style={styles.container}>
                  <Button onPress={this.goToComponent.bind(this)}/> 
              </View>
      }
}

export default withNavigation(ComponentWithButton);