我不知道如何在子组件中使用反应导航

时间:2019-07-01 18:44:48

标签: javascript reactjs react-native react-navigation

我花了最糟糕的时间试图弄清楚如何在双重嵌套的子组件中使用反应导航。我已经尝试过使用回调函数并将导航作为道具,但是我无法弄清楚。有人介意看看吗?

我尝试使用回调,也将导航作为道具传递。我遇到很多错误,例如“找不到道具,找不到导航等”。非常感谢您的帮助。

//main function (App.js)

import React from 'react';
import Bar from "./Bar"
import { StyleSheet, Text, View, Image, SafeAreaView, Dimensions, Button } from 'react-native';
import { createAppContainer, createStackNavigator, StackActions, NavigationActions } from 'react-navigation';


function HomeScreen() {


  return (
      <View>
        <Bar navigation = {this.navigation}/>
      </View>



  );
}


function DetailsScreen() {
  return (
    <Text>Hello from Details screen</Text>
  )
}

const AppNavigator = createStackNavigator({
  Home: {
    screen: HomeScreen,
  },
  Details: {
    screen: DetailsScreen,
  },
}, {
    initialRouteName: 'Home',
});

export default createAppContainer(AppNavigator);


//First Child Component

import React, { Component } from "react";
import {
  Image, StyleSheet, View, Text,Dimensions
} from "react-native";
import Animated from "react-native-reanimated";
import BarButton from "./BarButton"

export default class Bar extends Component {
  bottombarcallback3 = () => this.props.scopeSpecificFunction23();
render() {
  return (
    <View style ={{
      width: 200,
      height: 200,
      backgroundColor: "#C0C0C0",
      flexDirection: 'row',
      justifyContent: 'space-between',
    }}>
      <BarButton navigation = {this.navigation} />
    </View>
  )
}
}

//final child component


import React, { Component } from "react";
import {
  Image, StyleSheet, View, Text,Dimensions, Button
} from "react-native";
import Animated from "react-native-reanimated";
import { createAppContainer, createStackNavigator, StackActions, NavigationActions, withNavigation } from 'react-navigation';

export default class BarButton extends Component {
render() {
  return (
    <View style = {{
      width: 80,
      height: 80,
      backgroundColor: "#DC143C",
    }}>
    <Button
        title="Go to Details"
        onPress={() => {this.props.navigation.navigate('Like')}}
      />
    </View>
  )
}
}

我只希望能够从子组件更改屏幕。

1 个答案:

答案 0 :(得分:0)

他们为react-navigation提供了一个higher order component,使您可以从树中的任何位置访问导航,尽管它仍然低于导航提供程序(StackNavigatior,TabNavigator等)。您可以将下部组件修改为如下所示:


// Extra code omitted 

import {withNavigation} from 'react-navigation';

class BarButton extends Component {
  render() {
    return (
      <Button
          title="Go to Details"
          onPress={() => {this.props.navigation.navigate('Like')}}
       />
    )
  }
}

export default withNavigation(BarButton)

如果您需要了解组件是否聚焦,则可以在完全相同的庄园中使用withNavigationFocus。这个更高阶的组件会将navigation注入到道具中,因此您无需钻探就可以使用它。

以下是withNavigation https://reactnavigation.org/docs/en/with-navigation.htmlwithNavigationFocus的文档:https://reactnavigation.org/docs/en/with-navigation-focus.html