如何从嵌套导航器组件调用父导航器

时间:2019-07-29 07:30:28

标签: react-native react-navigation

我变得不确定,不是对象(评估'this.props.navigation') 当我在嵌套组件中调用它时

我也尝试将withNavigation用于嵌套的导航器和组件。

根导航器在分开的位置

const stackNavigator = createStackNavigator({
    Home: {
        screen: TabNav
    },
    ProductsList:{
        screen: ProductsList
    };

const MainNavigation = createAppContainer(stackNavigator);

export default MainNavigation;

嵌套导航器分隔

const TabNav = createBottomTabNavigator({
    Home:{
        screen: Home,   
    },
    Whislist: WishList,
    Cart: Cart,
    Account: MyAccount
});

export default TabNav;

这以及如何在App.js中实现我的使用根导航器

const App = () => {
  return (
    <MainNavigation/>
  );
};

export default App; 

这是我的主页组件,功能,报价和类别组件,工作正常

class Home extends Component {
 product =[];
 offers=[]
 category=[]


 nav() {
  this.props.navigation.navigate("ProductsList");
 };
 state = {
  products: this.products,
  offers: this.offer,
  categories: this.category
 };
 render() {
  return (
   <View style={{ flex: 1}}>
    <ScrollView>
     <FeaturedProducts items={this.state.products}></FeaturedProducts>
     <Offers offers={this.state.offers}></Offers>
     <Categories nav={this.nav} categories={this.state.categories}> </Categories>
    </ScrollView>
   </View>
  );
 };
};
export default Home;

反应:“ 16.8.6”, react-native:“ 0.60.4”, react-navigation:“ ^ 3.11.1”

1 个答案:

答案 0 :(得分:0)

由于您没有提供完整的代码,所以我不知道嵌套组件的含义。我想您的情况如下:

<View>
   <NestedComponent/> //Inside this component you are trying to do this.props.navigation 
</View>

您必须使用withNavigation或将导航道具传递给组件:

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

然后,您可以在嵌套组件中调用this.props.navigation

编辑。

您似乎没有将功能绑定到组件this。您必须使用箭头功能:

nav=()=>{
this.props.navigation.navigate("ProductsList")
}

或将函数绑定到构造函数中,以执行以下操作:

constructor(props){
   super(props)
   this.nav = this.nav.bind(this);
}