React study notes - Context
introduce
Context provides a way to share such values between components without having to explicitly pass props through the layers of the component tree
Context provides a way to pass data between component trees without manually adding props to each layer of components
The main application scenario of Context is that many components at different levels need to access the same data. Please use with caution,
因为这会使得组件的复用性变差
API
React.createContext
const MyContext = React.createContext(defaultValue);
Use this API to create an object, and the component will read the corresponding value Context
from the nearest one . Provider
Only when the tree species where the component is located does not exist Provider
, defaultValue
the parameter will take effect
Context.Provider
<MyContext.Provider value={某个值}/>
Context
object will return a Provider
component
- Provider accepts a
value
property and passes it to the consumer component - When the value of the Provider's
value
property changes, all internal consumer components will be re-rendered - The context will be re-rendered according to the reference identifier, so when passing
value
an object to it, you need to pay attention: when re-rendering, unexpected renderingProvider
may be triggered .Consumer
To prevent this, promote the state tovalue
the parent node'sstate
Context.Consumer
<MyContext.Consumer>
{value => /* 基于 context 值进行渲染*/}
</MyContext.Consumer>
Context
object will return a Consumer
component
- A function is required as a child element, the function receives
context
a value, and returns aReact节点
- The value passed to the function is equivalent to the provided value
value
closest to this one above the component tree . If there is no counterpart , the argument is equivalent to the one passed tocontext
Provider
value
Provider
value
createContext()
defaultValue
Class.contextType
This property allows you to use this.context
to get Context
the most recent value. You can access it in any life cycle, including render
functions
const MyContext = React.createContext()
class MyClass extends React.Component {
render() {
let value = this.context;
/* 基于这个值进行渲染工作 */
}
}
MyClass.contextType = MyContext
At the same time, you can also use the class property initialization public class fields
in the experimental syntaxstatic
contextType
const MyContext = React.createContext()
class MyClass extends React.Component {
static contextType = MyContext
render() {
let value = this.context;
/* 基于这个值进行渲染工作 */
}
}
Context.displayName
context
object accepts a string displayName
named property
, which React DevTools uses to determine context
what to display