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 badges1 Answer
Reset to default 6It 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
版权声明:本文标题:javascript - React context provider and consumer - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744854428a2628690.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论