新的 context api 应该如何与 React Native navigator 一起使用? [英] How should the new context api work with React Native navigator?

查看:27
本文介绍了新的 context api 应该如何与 React Native navigator 一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我按照以下示例使用 React Navigator 创建了一个多屏应用:

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

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

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

export default App;

现在我想使用 新的内置上下文 api 添加全局配置状态,这样我就可以拥有一些可以在多个屏幕上操作和显示的通用数据.

Now I'd like to add a global configuration state using the new builtin context api, so I can have some common data which can be manipulated and displayed from multiple screens.

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

The problem is context apparently requires components having a common parent component, so that context can be passed down to child components.

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

How can I implement this using screens which do not share a common parent as far as I know, because they are managed by react navigator?

推荐答案

你可以这样做.

创建新文件: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>
);

index.js 上用上下文提供程序组件包装你的根组件.

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

<GlobalContextProvider>
  <App />
</GlobalContextProvider>

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

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 (
      <View>
        <Text>Is online: {this.props.global.isOnline}</Text>
      </View>
    )
  }
}

export default withGlobalContext(HomeScreen);

您还可以创建多个上下文提供者来分离您的关注点,并在您想要的屏幕上使用 HOC 消费者.

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

这篇关于新的 context api 应该如何与 React Native navigator 一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆