反应上下文提供者和消费者 [英] React context provider and consumer

查看:121
本文介绍了反应上下文提供者和消费者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ThemeContext.js

ThemeContext.js

import React from 'react';

const ThemeContext = React.createContext(null);

export default ThemeContext;

父组件

import ThemeContext from './ThemeContext';

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

组件C低于组件D.

import ThemeContext from './ThemeContext';

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

让我含糊不清的是我们正在导入ThemeContext .js来自提供者(组件A)和消费者(组件C)。那么两个组件如何共享一个ThemeContext实例(消费者如何访问提供者上下文而不共享一个),两者都有自己的ThemeContext?

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

推荐答案

这是允许在两者之间共享值的 Provider parent和 Consumer 后代之间的关系他们。

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'}> 作为父级,因此它可以访问绿色上下文值为 coloredTheme 回调参数。

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


都有自己的ThemeContext?

both have their own ThemeContext?

ES模块被评估一次并产生单例。 ThemeContext 是上下文对象。它在 A C 模块中相同。

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

这篇关于反应上下文提供者和消费者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆