我正在尝试制作动态主题,但是我遇到了问题。当我使用Provider和Consumer使用React.context时,我的应用程序在屏幕上不显示任何内容。
这是我的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>
);
}
当我尝试运行应用程序时,屏幕为空白。控制台中没有任何警告。我不知如何解决此问题。
答案 0 :(得分:0)
您的道具没有传递给AppContainer:
export default class App extends React.Component {
render() {
return (
<ThemeProvider>
<AppContainer {...this.props} />
</ThemeProvider>
);
}
}
答案 1 :(得分:0)
您没有从Context.Consumer返回任何内容
编辑:总比没有好。