0

我正在尝试制作动态主题,但我遇到了问题。当我将 React.context 与 Provider 和 Consumer 一起使用时,我的应用程序不会在屏幕上显示任何内容。

这是我的 App.js

import React from 'react';
import Route from './route/Route';
import { ThemeProvider } from './reusables/theme/themeContext';

const AppContainer = createAppContainer(Route);

export default class App extends React.Component {
  render() {
    return (
      <ThemeProvider>
        <AppContainer/>   
      </ThemeProvider>
    );
  }
}

- 路线

import { createStackNavigator } from "react-navigation";

const BaseStack = createStackNavigator(
{
    Overview: { 
      screen: OverviewScreen,
      navigationOptions: { header: null, },
    },
    {
      initialRouteName: 'Overview',
    }
})
export default BaseStack;

-- 提供者类

import React, {Component} from 'react';

const ThemeContext = React.createContext({
    themeColor: '#f45',
    changeThemeColor: () => null,    
});

export const ThemeConsumer = ThemeContext.Consumer;

export class ThemeProvider extends Component {
    state = {
        themeColor: '#f45',
    }

    changeThemeColor = (themeColor) => {
        this.setState({ themeColor });
    }

    render() {
        return (
            <ThemeContext.Provider 
                value={{
                    themeColor: this.state.themeColor,
                    changeThemeColor: this.changeThemeColor,
                }}>
                { this.props.children }
            </ThemeContext.Provider>
        )
    }
}

-- 子组件

import React, { Component } from 'react';
import { View, StatusBar, ScrollView, ToastAndroid } from 'react-native';

/* --- STYLES - COLORS ---*/
import gStyle from '../styles/Style.global';
import { ThemeConsumer } from '../reusables/theme/themeContext';

export default class OverviewScreen extends Component {
    constructor(props) {
        super(props);
        this.state = {
        }
    }

    render() {
        return (
            <ThemeConsumer>
                {( themeColor ) => {
                    <View style={[{backgroundColor: themeColor}, gStyle.container]}>
                        <StatusBar hidden/>
                        {this.overviewPage()}
                    </View>
            }}
        </ThemeConsumer>
    );
}

当我尝试运行应用程序屏幕是空白的。控制台没有警告。我不知道如何解决这个问题。

4

2 回答 2

0

您的道具没有被传递给 AppContainer:

export default class App extends React.Component {
  render() {
    return (
      <ThemeProvider>
        <AppContainer {...this.props} />   
      </ThemeProvider>
    );
  }
}
于 2019-01-06T09:37:17.037 回答
0

您没有从 Context.Consumer 返回任何内容

编辑:迟到总比没有好。

于 2020-05-17T10:55:19.143 回答