admin管理员组

文章数量:1410705

ThemeContext.js

import React from 'react';

const ThemeContext = React.createContext(null);

export default ThemeContext;

Parent ponent

import ThemeContext from './ThemeContext';

class A extends React.Component {
  render() {
    return (
      <ThemeContext.Provider value={'green'}>
        <D />
      </ThemeContext.Provider>
    );
  }
}

Component C is below ponent D.

import ThemeContext from './ThemeContext';

class C extends React.Component {
  render() {
    return (
      <ThemeContext.Consumer>
        {coloredTheme =>
          <div style={{ color: coloredTheme }}>
            Hello World
          </div>
        }
      </ThemeContext.Consumer>
    );
  }
}

What makes me vague is that we are importing "ThemeContext.js" from the provider(ponent A) and the consumer(ponent C). So how could the two ponents share a single ThemeContext instance( how does the consumer access the providers context without sharing a single one) , both have their own ThemeContext?

ThemeContext.js

import React from 'react';

const ThemeContext = React.createContext(null);

export default ThemeContext;

Parent ponent

import ThemeContext from './ThemeContext';

class A extends React.Component {
  render() {
    return (
      <ThemeContext.Provider value={'green'}>
        <D />
      </ThemeContext.Provider>
    );
  }
}

Component C is below ponent D.

import ThemeContext from './ThemeContext';

class C extends React.Component {
  render() {
    return (
      <ThemeContext.Consumer>
        {coloredTheme =>
          <div style={{ color: coloredTheme }}>
            Hello World
          </div>
        }
      </ThemeContext.Consumer>
    );
  }
}

What makes me vague is that we are importing "ThemeContext.js" from the provider(ponent A) and the consumer(ponent C). So how could the two ponents share a single ThemeContext instance( how does the consumer access the providers context without sharing a single one) , both have their own ThemeContext?

Share Improve this question asked Aug 22, 2018 at 9:24 Henok TesfayeHenok Tesfaye 9,62015 gold badges51 silver badges92 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

It is the relationship between Provider parent and Consumer descendants that allows to share values between them.

<ThemeContext.Consumer> in C has <ThemeContext.Provider value={'green'}> as parent, so it's able to access green context value as coloredTheme callback parameter.

both have their own ThemeContext?

ES modules are evaluated once and result in singletons. ThemeContext is context object. It is same in A and C modules.

本文标签: javascriptReact context provider and consumerStack Overflow