问题描述
鉴于您已将上下文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 (将#修改为@)