简体   繁体   中英

React Native: Convert State/Context code from Functional Component to Class Component

I have a simple React-Native app setup in which I use Context to share some data throughout components. I have some code setup for functional components but I would like to convert it to Class component code. Anyone who could help me further?

All that needs to be changed is the way context in de screens and state is handled.

UserContext.js (this one doesn't need changing just putting it here for context.)

import { createContext } from 'react'

export const UserContext = createContext(null);

AccountScreen.js

export default function AccountScreen() {
    const { User, setUser } = useContext(UserContext);

    return (
        <View>
            <Text>ID: {User}</Text>
        </View>
    )
}

App.js

export default function App() {

  const [User, setUser] = useState("yessir");

    return (
      <UserContext.Provider value={{User, setUser}}>
        <PaperProvider theme={theme}>
          <NavigationContainer>
            <Stack.Navigator>
              <Stack.Screen name="Register" component={RegisterScreen} options={{ headerShown: false}}/>
              <Stack.Screen name="Login" component={LoginScreen} options={{ headerShown: false}}/>
              <Stack.Screen name="Home" component={Home} options={{ headerShown: false }} />
            </Stack.Navigator>
          </NavigationContainer>
        </PaperProvider>
      </UserContext.Provider>
    );
}

A simple way is to write a higher-order component (HOC) with can provide user context props to any component.


import { createContext } from "react";

export const UserContext = createContext(null);

const withUserContext = (Component) => {
  return (
    <UserContext.Consumer>
      {(userContext) => {
        return <Component userContext={userContext} />;
      }}
    </UserContext.Consumer>
  );
};

export default withUserContext;


AccountScreen.js

import React from "react";
import withUserContext from "./withUserContext";

class AccountScreen extends React.Component {
  render() {
    const { User, setUser } = this.props.userContext;
    return (
      <View>
        <Text>ID: {User}</Text>
      </View>
    );
  }
}

export default withUserContext(Account);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM