[英]React context provider and consumer
ThemeContext.js ThemeContext.js
import React from 'react';
const ThemeContext = React.createContext(null);
export default ThemeContext;
Parent component 父组件
import ThemeContext from './ThemeContext';
class A extends React.Component {
render() {
return (
<ThemeContext.Provider value={'green'}>
<D />
</ThemeContext.Provider>
);
}
}
Component C is below component D. 组分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>
);
}
}
What makes me vague is that we are importing "ThemeContext.js" from the provider(component A) and the consumer(component C). 让我模糊的是我们从提供者(组件A)和使用者(组件C)导入“ThemeContext.js”。 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?
那么两个组件如何共享一个ThemeContext实例(消费者如何在不共享一个的情况下访问提供者上下文),两者都有自己的ThemeContext?
It is the relationship between Provider
parent and Consumer
descendants that allows to share values between them. Provider
父级和Consumer
后代之间的关系允许在它们之间共享值。
<ThemeContext.Consumer>
in C
has <ThemeContext.Provider value={'green'}>
as parent, so it's able to access green
context value as coloredTheme
callback parameter. C
<ThemeContext.Consumer>
将<ThemeContext.Provider value={'green'}>
作为父级,因此它可以将green
上下文值作为coloredTheme
回调参数访问。
both have their own ThemeContext?
两者都有自己的ThemeContext?
ES modules are evaluated once and result in singletons. ES模块被评估一次并产生单例。
ThemeContext
is context object. ThemeContext
是上下文对象。 It is same in A
and C
modules. 在
A
和C
模块中是相同的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.