如何在React Native中实现Context API

时间:2019-04-01 08:00:31

标签: javascript reactjs react-native

我刚刚开始寻找全局更改主题,发现Context可以做到这一点,

但是我在将示例代码实现到我的React Native项目时遇到问题,

我尝试了以下代码:

//themeContext.js

const themes = {
  light: {
    foreground: '#000000',
    background: '#eeeeee',
  },
  dark: {
    foreground: '#ffffff',
    background: '#222222',
  },
};

export const ThemeContext = React.createContext({
  theme: themes.dark,
  toggleTheme: () => {},
})

//App.js

import React, { Component } from 'react';
import {InitialScreen} from './routes/routes';
import { ThemeContext } from './Component/themeContext';

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state={
      theme:themes.light,
      toggleTheme:this.toggleTheme
    }
    this.toggleTheme=()=>{
      this.setState(state=>({
        theme:state.theme === themes.dark ? themes.light : themes.dark
      }))
    }
  }

  render() {
    console.disableYellowBox = true;
    return (
      <ThemeContext.Provider value={this.state}>
        //this is Login.js
        <InitialScreen/>
      </ThemeContext.Provider>
    );
  }
}

//Login.js

import React from 'react';
import { Text, TouchableOpacity, View } from 'react-native';
import { ThemeContext } from '../Component/themeContext';

export default class Login extends Component {
  render() {
    return (
      <ThemeContext.Consumer>
        {({theme, toggleTheme})=>{
          <View style={{backgroundColor:theme.background}}>
            <Text>{this.state}</Text>
          </View>
        }}
      </ThemeContext.Consumer>
    );
  }
}

但是我有一个错误Can't find variable: Component,我不知道应该把import React from 'react';放在哪里,因为我认为我已经在Component和{{ 1}}

任何帮助将不胜感激

3 个答案:

答案 0 :(得分:0)

将下一个字符串替换为Login.js的顶部,而不是

import React from 'react';

使用

import React, { Component } from 'react';

另一种方法是替换

export default class Login extends Component {
}

使用

export default class Login extends React.Component {
}

答案 1 :(得分:0)

在App.js中,通过将App替换为Component来更新React.Component组件类的定义,如下所示:

export default class App extends React.Component {

   /* existing component code */
}

在Login.js中也进行相同的更改:

export default class Login extends React.Component {

   /* existing component code */
}

这些更改将导致LoginApp组件从已导出Component的{​​{1}}对象定义的React类扩展而来。

答案 2 :(得分:0)

themeContext.js 文件中的问题

您使用createContext(),但是您没有导入React,所以您将找不到React

应该是这样

import React from 'react';
export const themes = {
  light: {
    foreground: '#000000',
    background: '#eeeeee',
  },
  dark: {
    foreground: '#ffffff',
    background: '#222222',
  },
};
export const ThemeContext = React.createContext({
  theme: themes.dark,
  toggleTheme: () => {},
});

Login.js

import React,{Component} from 'react';