新的上下文api应该如何与React Native导航器一起使用?

Tom*_*Tom 14 reactjs react-native react-navigation react-context

我按照这个例子使用React Navigator创建了一个多屏幕应用程序:

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

const App = createStackNavigator({
  Home: { screen: HomeScreen },
  Profile: { screen: ProfileScreen },
});

export default App;
Run Code Online (Sandbox Code Playgroud)

现在我想使用新的内置上下文api添加一个全局配置状态,因此我可以使用一些可以在多个屏幕上操作和显示的公共数据.

问题是上下文显然需要具有共同父组件的组件,以便上下文可以向下传递给子组件.

我如何使用不知道共享父母的屏幕来实现这一点,因为它们是由react navigator管理的?

Ded*_*zah 14

你可以这样做.

创建新文件: 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 (
      <GlobalContext.Provider
        value={{
          ...this.state,
          switchToOnline: this.switchToOnline,
          switchToOffline: this.switchToOffline
        }}
      >
        {this.props.children}
      </GlobalContext.Provider>
    )
  }
}

// create the consumer as higher order component
export const withGlobalContext = ChildComponent => props => (
  <GlobalContext.Consumer>
    {
      context => <ChildComponent {...props} global={context}  />
    }
  </GlobalContext.Consumer>
);
Run Code Online (Sandbox Code Playgroud)

index.js包装与上下文提供组件的根组件.

<GlobalContextProvider>
  <App />
</GlobalContextProvider>
Run Code Online (Sandbox Code Playgroud)

然后在屏幕上HomeScreen.js使用这样的消费者组件.

import React from 'react';
import { View, Text } from 'react-native';
import { withGlobalContext } from './GlobalContext';

class HomeScreen extends React.Component {
  render () {
    return (
      <View>
        <Text>Is online: {this.props.global.isOnline}</Text>
      </View>
    )
  }
}

export default withGlobalContext(HomeScreen);
Run Code Online (Sandbox Code Playgroud)

您还可以创建多个上下文提供程序来分离您的问题,并在您想要的屏幕上使用HOC使用者.

  • 您应该添加原因,以使其更好,因为此评论目前还没有很大帮助。 (4认同)