将导航传递功能反应到堆栈导航器,然后再响应头组件

时间:2019-08-29 16:06:26

标签: react-native react-navigation expo

我有一个带有react-navigation v3的expo react native应用。

我将一个SignOut函数从我的主应用传递给我的一个堆栈导航器的标头组件。我只想传递一次此标头,所以不想将其添加到每个屏幕的navigationOptions中。

我在访问MainStackNavigator中的道具并将函数传递给我的组件时遇到麻烦。

主应用

 render () {
        return (
            <View style={styles.container}>
                <AppNavigator screenProps={{ signOut: this.signOut }}/>
            </View>
        );
    }

AppNavigator

export default createAppContainer(
    createSwitchNavigator({
        // You could add another route here for authentication.
        // Read more at https://reactnavigation.org/docs/en/auth-flow.html
        Main: MainStackNavigator,
    },
    {
        initialRouteName: 'Main'
    })
);

MainStackNavigator

export default createStackNavigator({
    Home: { 
        screen: HomeScreen, 
    }
},{
    initialRouteName: 'Home',
    defaultNavigationOptions : {
        headerTitle: <LogoTitle signOut={this.screenProps.signOut}/>,
        headerMode: 'screen',
    }
});

因此,当我传入组件LogoTitle时,如何在这一点上访问screenProps?

2 个答案:

答案 0 :(得分:2)

在react中传递一些东西是非常典型的任务,在向您展示答案之前,我们需要了解react并不喜欢无处不在的注入,默认情况下,您需要将其传递给孩子。大多数情况下,这意味着如果您遇到问题,实际上您的父母与子女的关系就会出现问题,要么上升要么下降。

因此,为了以某种通用的方式解决您的问题,您可以考虑传递一个可以更改lowercase而不是screenProps的函数,除非screenProps总是只读孩子们的观点。

有很多方法可以实现。我只是通过钩子向您展示一种方式

screenProps

从现在开始,您的孩子随时可以通过 const [props, setProps] = useState({ default props }) return ( <ChildrenComp onChange={setProps} /> ) 随时更换道具。

现在,我们又回到了过去,将onChange传递给需要它们的孩子。

我不喜欢props的简单问题,如果您知道您的父母和孩子,则应该构建代码来简化这一工作。如果确实需要,则可以进行redux;如果没有其他选择,则可以进行useContext。一开始不要使用redux,这对入门级编程没有帮助,尤其是当您不确定100%redux中的prop是什么时。

答案 1 :(得分:1)

我认为您无法在screenProps函数中访问createStackNavigator。实际上没有必要将其作为screenProps传递,因为screenProps are accessible in screens/views not Navigators。此外,AppNavigator中有no screenProps prop

正确的方法是通过signOut文件中定义的auth.js函数,该函数可从任何地方访问。如果您想对用户的退出做出反应,请使用redux并更新状态并对该更新做出反应。