简体   繁体   English

是否可以从 react-native 中的类组件访问功能上下文?

[英]Is it possible to access functional context from class component in react-native?

I'm currently having react-native project v0.63.2 and using @react-navigation-5.我目前正在使用 react-native 项目 v0.63.2 并使用 @react-navigation-5。 Navigation from splash screen, login screen and tab screen is based from context.从初始屏幕、登录屏幕和选项卡屏幕导航是基于上下文的。

appContext.js应用上下文.js

import React from 'react';
const AppContext = React.createContext({IsLoading: true, IsLoggedIn: false});
export default AppContext;

navigationContainer.js导航容器.js

import AppContext from './appContext';
const StackApp = createStackNavigator();
export const StackNavigator = () => {
  const [appState, setAppState] = React.useState({});
  const state = { appState, setAppState };
  React.useEffect(() => {
    setAppState({ IsLoading: true, IsLoggedIn: false });
  }, []);

  return (
    <AppContext.Provider value={state}>
      {appState.IsLoading ? (
        <SplashScreen />
      )
        : (
          <NavigationContainer>
            <StackApp.Navigator>
              {
                appState.IsLoggedIn
                  ?
                  <>
                    <StackApp.Screen name='BottomTabScreen' component={BottomTabScreen} options={{ headerShown: false }} />
                  </>
                  :
                  <StackApp.Screen name='LoginScreen' component={NavigatorLogin} options={{ headerShown: false }} />
              }
            </StackApp.Navigator>
          </NavigationContainer>
        )}
    </AppContext.Provider>
  )
}

I recreate new login page with a class component.我用一个类组件重新创建了新的登录页面。 It can load all the previous way as functional component.它可以加载所有以前的方式作为功能组件。 But I unable to modify/update the context for IsLoggedIn: true .但我无法修改/更新IsLoggedIn: true的上下文。

What I have tried:- initLogin.js我尝试过的:- initLogin.js

import AppContext from '../navigator/appContext';
const AppState = ({ newContext }) => {
  const { setAppState } = React.useContext(AppContext);
  console.log('setAppState:=> ' + JSON.stringify(setAppState));
  console.log('newContext:=> ' + JSON.stringify(newContext));
  setAppState(newContext);
}
export class initSignIn extends Component {
   onPressLogin = () => {
      AppState({ IsLoggedIn: true });
   }
}

This will raise error hooks rules这将引发错误挂钩规则

Invalid hook call.无效的钩子调用。 Hooks can only be called inside of the body of a function component Hooks 只能在函数组件内部调用

I also tried use static context.我也尝试使用静态上下文。 No error but value undefined indicated the key IsLoggedIn is not there.没有错误,但值未定义表明键IsLoggedIn不存在。

Some of my reference:我的一些参考:

  1. How to use React Context inside function of Class component 如何在 Class 组件的函数内使用 React Context
  2. SO Answer所以答案

I added snack minimal script.我添加了零食最小脚本。 Might having error due to UI Kitten theme I use.由于我使用的 UI Kitten 主题,可能会出错。 I'm not familiar with snack Minimal Script我不熟悉小吃最小脚本

This would be a working example that uses context with a class component.这将是一个使用上下文与类组件的工作示例。 Remember that you can use only one context when you are accessing it from a class.请记住,当您从一个类访问它时,您只能使用一个上下文。

Here I have created a button component which would update the context.在这里,我创建了一个按钮组件来更新上下文。 As you can see i have function inside the context which would update the context which we pass the setAppState function from useState.正如你所看到的,我在上下文中有函数,它会更新我们从 useState 传递 setAppState 函数的上下文。

  const AppContext = React.createContext({
      appState: { IsLoading: true, IsLoggedIn: false },
      setAppState: () => {},
    });
    
    export default function App() {
      const [appState, setAppState] = React.useState({
        IsLoading: false,
        IsLoggedIn: false,
      });
    
      return (
        <AppContext.Provider value={{ appState, setAppState }}>
          <View style={styles.container}>
            <Text style={styles.paragraph}>{JSON.stringify(appState)}</Text>
            <Button />
          </View>
        </AppContext.Provider>
      );
    }
    
    class Button extends React.PureComponent {
      render() {
        return (
          <TouchableOpacity
            onPress={() =>
              this.context.setAppState({
                IsLoading: !this.context.appState.IsLoading,
                IsLoggedIn: true,
              })
            }>
            <Text>Update</Text>
          </TouchableOpacity>
        );
      }
    }
    Button.contextType = AppContext;

Url for snack https://snack.expo.io/@guruparan/contextwithclass零食网址 https://snack.expo.io/@guruparan/contextwithclass

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 react-native 如何将功能组件更改为类组件 - react-native how to change functional component to class component 如何将 react-native 道具从功能组件传递到 class 组件 - How to pass react-native props from functional component to class component React Native:将状态/上下文代码从功能组件转换为 Class 组件 - React Native: Convert State/Context code from Functional Component to Class Component 是否可以在本机反应中从另一个 class 组件访问 useRef 变量? - Is it possible to access a useRef variable from another class component in react native? 我们如何在 react-native 功能组件中声明和使用 class 而不用 React.Component 扩展它? - How can we declare and use class in react-native functional component without extending it with React.Component? 如何将 function 从 FUNCTIONAL 传递给 CLASS 组件并在渲染外部访问它(没有 prop ),在反应 js 中使用上下文? - How to pass function from FUNCTIONAL to CLASS component and access it outside of render( without prop ), using context in react js? 将数据从功能组件传递到父类组件反应原生 - Passing data from a functional component to a parent class component react native 从 class 组件获取数据到功能组件 - React Native - Getting data from a class component to Functional component - React Native 是否可以从 React Class 组件到功能组件进行道具钻取? - Is it possible to do prop drilling from React Class Component to Functional Component? 使用 React 从功能组件中的 class 组件访问 ref - Access ref from class component in functional component with React
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM