将上下文连接到组件内部的组件

问题描述

鉴于您已将上下文AuthContext.js设置为:

import React from 'react'

const AuthContext = React.createContext();

export const AuthProvider = AuthContext.Provider
export const AuthConsumer = AuthContext.Consumer

export default AuthContext

您将AuthContext这样从父级传递给子级组件:

<AuthProvider value={authContext}>
    <NavigationContainer>
      <Stack.Navigator>
        {state.userToken == null ? (
          <Stack.Screen name="Sign In" component={SignInScreen} />
        ) : (
          <Stack.Screen name="Home" component={HomeScreen} />
        )}
      <Stack.Screen name="Registration" component={Registration} />
      </Stack.Navigator>
    </NavigationContainer>
    </AuthProvider>

在子组件中,您可以像这样获得AuthContext:

class SignInScreen extends Component {
    static contextType = AuthContext
        state = {
           userName: '',password: ''
        }
      render(){
        const { signIn } = this.context 
      return (<Button title='Submit' onPress={() => signIn()}></Button>)
      }

如果SignInScreen调用了另一个组件注册,则上级组件中的化简器设置正确:

class SignInScreen extends Component {
        static contextType = AuthContext
            state = {
               userName: '',password: ''
            }
          render(){
            const { signIn } = this.context 
           if (flag){
                return (<Button title='Submit' onPress={() => signIn()}></Button>)
           }
           else {
           return (<Button title='Submit' onPress={() => this.props.navigation.navigate('Registration')}></Button>)
           }
          }

一个人如何从注册中调用AuthContext。我尝试了与SignInScreen中使用的方法相同的方法,但是它不起作用。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...