React的Context API Cosumer未呈现子级

时间:2018-08-12 13:35:48

标签: reactjs ecmascript-6 styled-components

我正在使用React Context API和本教程实现主题切换器 https://www.youtube.com/watch?time_continue=1&v=oDgxUodLwGU

我首先创建了上下文

    export default React.createContext({
       theme: dark
    });

然后我定义了主题(深色和浅色)

然后我创建了一个组件(TodoList)

import React from 'react';
import styled from 'styled-components';

const List = styled.ul`
    background: ${props => {
        debugger;
        props.theme.background;
    }};
    color: ${props => props.theme.color};
    font-family: sans-serif;
    font-size: 20px;

    li {
        line-height: 36px;
    }
`;

const TodoList = () => {
    debugger;
    return (
        <List>
            <li>item1</li>
            <li>item2</li>
            <li>item3</li>
        </List>
    );
};

export default TodoList;

然后在我的应用程序组件中,我使用了以下代码

import React, {
  Component
} from 'react';
import './App.css';
import TodoList from './components/TodoList';
import ThemeSwitcher from './components/ThemeSwitcher';
import * as themes from './styles/themes';
import ThemeContext from './styles/themes/context';
import { ThemeProvider } from 'styled-components';

class App extends Component {
  state = {
    theme: themes.dark,
  };

  toggleTheme = () => {
    this.setState({ theme: this.state.theme === themes.dark ? themes.light : themes.dark });
  };

  render() {
    console.log(this.state.theme);
    return (
      <div id="root">
        <ThemeContext.Provider value={this.state}>
          <ThemeSwitcher toggleTheme={this.toggleTheme} />
          <ThemeContext.Consumer>
            {theme => {
              <ThemeProvider theme={theme}>
                <TodoList />
              </ThemeProvider>
            }}
          </ThemeContext.Consumer>
        </ThemeContext.Provider>
      </div>
    );
  }
}

export default App;

当我在ThemeContext.Consumer之外使用TodoList组件时,它可以很好地渲染,但是在它内部则永不渲染。 TodoList组件中的断点永远不会被点击...

我也尝试不理会ThemeContext.Consumer并使用以下代码段:

<ThemeProvider theme={theme}>
          <TodoList />
        </ThemeProvider>

呈现的组件。

我可能做错了什么? 预先感谢。

1 个答案:

答案 0 :(得分:0)

我能够确定问题所在,是下面的代码段:

FactoryB

应该是

<ThemeContext.Consumer>
            {theme => {
              <ThemeProvider theme={theme}>
                <TodoList />
              </ThemeProvider>
            }}
          </ThemeContext.Consumer>