簡體   English   中英

是否可以從 react-native 中的類組件訪問功能上下文?

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

我目前正在使用 react-native 項目 v0.63.2 並使用 @react-navigation-5。 從初始屏幕、登錄屏幕和選項卡屏幕導航是基於上下文的。

應用上下文.js

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

導航容器.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>
  )
}

我用一個類組件重新創建了新的登錄頁面。 它可以加載所有以前的方式作為功能組件。 但我無法修改/更新IsLoggedIn: true的上下文。

我嘗試過的:- 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 });
   }
}

這將引發錯誤掛鈎規則

無效的鈎子調用。 Hooks 只能在函數組件內部調用

我也嘗試使用靜態上下文。 沒有錯誤,但值未定義表明鍵IsLoggedIn不存在。

我的一些參考:

  1. 如何在 Class 組件的函數內使用 React Context
  2. 所以答案

我添加了零食最小腳本。 由於我使用的 UI Kitten 主題,可能會出錯。 我不熟悉小吃最小腳本

這將是一個使用上下文與類組件的工作示例。 請記住,當您從一個類訪問它時,您只能使用一個上下文。

在這里,我創建了一個按鈕組件來更新上下文。 正如你所看到的,我在上下文中有函數,它會更新我們從 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;

零食網址 https://snack.expo.io/@guruparan/contextwithclass

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM