class=”markdown_views prism-atom-one-dark”>
context can be used to pass parameters from parent components to child components or from grandparent components to grandchild components.
Note that data flow is one-way, and child components cannot be passed to parent components
Usage:
- In the parent component MyComponent
const AContext = React.createContext(initial value)
function MyComponent(){
render (){
AContext.provider value={
this.state} //You can pass an object
B/B
/AContext.provider>
}
}
const AContext = React.createContext (initial value)
//The initial value here is similar to the initial value of useState, you can pass an empty value
AContext.provider value={
this.state} //You can pass an object
B/B
/AContext.provider>
- At this time, if component B contains subcomponent C, you don’t need to specify the data that needs to be passed down, and C will get the
subcomponent B component by default
function B(){
return(
C/C
);
}
- Specify the contextType to read the current context value, and React will find the nearest Provider to the upper layer
In the grandson component C
Introduce AContext from the parent component MyComponent
function C(){
static contextType = AContext;
render (){
return <Button theme={
this.context} //theme value is this.state in the parent component MyComponent component
}
}
Compared with props and state, React’s Context can realize cross-level component communication
https://zhuanlan.zhihu.com/p/110331535
https://zh-hans.reactjs.org/docs/context.html