【问题标题】:navigation between component in react native反应原生组件之间的导航
【发布时间】:2019-01-22 17:13:18
【问题描述】:

我需要在 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

我有错误 undefined is not an object (evalating "this.props.navigation.push")

我的堆栈导航器是这样的:

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

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

【问题讨论】:

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


    【解决方案1】:

    您没有将导航道具传递给 &lt;ComponentWithButton /&gt;

    做这样的事情

    &lt;ComponentWithButton navigation={this.props.navigation}/&gt;

    方法也应该是

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

    如果我记得

    【讨论】:

    • @Yapoto 如果它是正确的答案,请检查它,以便我得到信任
    • 你太快了,等2分钟;)
    【解决方案2】:

    react-navigation 有一个 withNavigation 函数,可以在你的任何组件中填充导航道具。就这样使用它:

    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);
    

    【讨论】:

    • 我不知道,但我想是的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多