如何在导航器中将不同的道具传递到不同的屏幕?

时间:2019-02-19 12:44:51

标签: javascript react-native react-navigation

我正在尝试创建具有不同类别过滤器的新闻应用。为此,我必须将道具传递到导航器中的不同屏幕,以便组件可以将道具用于获取api。 例如:

export default createMaterialTopTabNavigator({
    Home: {
        screen: HomeScreen,
        navigationOptions:{
            tabBarLabel: "Home",
        },
        props: {id: 1}
    },
    BeautyScreen: {
        screen: HomeScreen,
        navigationOptions:{
            tabBarLabel: "Beauty tips",
        },
        props: {id: 2}
    },
    BusinessScreen: {
        screen: HomeScreen,
        navigationOptions:{
            tabBarLabel: "Business related",
        },
        props: {id: 3}
    },
    CarsScreen: {
        screen: HomeScreen,
        navigationOptions:{
            tabBarLabel: "Cars related",
        },
        props: {id: 4}
    },
)}

如您所见,我可以将相同的HomeScreen组件与不同的道具一起使用,例如,我可以传入api:fetch("https://some-api.com/?category=" + navigations.props.id)

这就是我现在所拥有的,我必须为具有不同api的基本相同组件为不同的屏幕创建不同的组件。

export default createMaterialTopTabNavigator({
    Home: {
        screen: HomeScreen,
        navigationOptions:{
            tabBarLabel: "Home",
        }
    },
    BeautyScreen: {
        screen: BeautyScreen,
        navigationOptions:{
            tabBarLabel: "Beauty tips",
        }
    },
    BusinessScreen: {
        screen: BusinessScreen,
        navigationOptions:{
            tabBarLabel: "Business related",
        }
    },
    CarsScreen: {
        screen: CarsScreen,
        navigationOptions:{
            tabBarLabel: "Cars related",
        }
    },

1 个答案:

答案 0 :(得分:0)

我刚刚发现反应导航v3支持此功能

BeautyScreen: {
    screen: OtherCategoriesScreens,
    navigationOptions:{
        tabBarLabel: "Beauty",
    },
    params: {
        categories: [
            {
                name: "Fashion",
                id: 144,
            },
            {
                name: "Make up",
                id: 143,
            },
        ]
    }
},

然后您可以在屏幕组件中使用this.props.navigation.getParam('categories')来获取参数。