How should the new context api work with React Native navigator?

后端 未结 4 779
野性不改
野性不改 2021-01-30 18:37

I created a multiscreen app using React Navigator following this example:

import {
  createStackNavigator,
} from \'react-navigation\';

const App = createStackN         


        
4条回答
  •  既然无缘
    2021-01-30 19:07

    You can make it like this.

    Create new file: GlobalContext.js

    import React from 'react';
    
    const GlobalContext = React.createContext({});
    
    export class GlobalContextProvider extends React.Component {
      state = {
        isOnline: true
      }
    
      switchToOnline = () => {
        this.setState({ isOnline: true });
      }
    
      switchToOffline = () => {
        this.setState({ isOnline: false });
      }
    
      render () {
        return (
          
            {this.props.children}
          
        )
      }
    }
    
    // create the consumer as higher order component
    export const withGlobalContext = ChildComponent => props => (
      
        {
          context => 
        }
      
    );
    

    On index.js wrap your root component with context provider component.

    
      
    
    

    Then on your screen HomeScreen.js use the consumer component like this.

    import React from 'react';
    import { View, Text } from 'react-native';
    import { withGlobalContext } from './GlobalContext';
    
    class HomeScreen extends React.Component {
      render () {
        return (
          
            Is online: {this.props.global.isOnline}
          
        )
      }
    }
    
    export default withGlobalContext(HomeScreen);
    

    You can also create multiple context provider to separate your concerns, and use the HOC consumer on the screen you want.

提交回复
热议问题