An overview of the
Provider component: A parent component that shares a value with the consuming component
Consumer component: Shares all child components that provide the value of the component
React. CreateContext create a Context object
When React renders a consumer component that subscribes to the Context object, the component reads the current Context value from the closest matching Provider in the component tree
const MyContext = React.createContext(defaultValue);
Copy the code
instructions
- When the component belongs to the component treeThere is no matchingto
Provider
To set the default initial valuedefaultValue
Before it goes into effect. - If it is to
undefined
Passed to theProvider
的value
Is the default initial valuedefaultValue
It won’t go into effect.
Context.Provider [can be nested (internal overwrites external)]
Each Context object returns a Provider React component, which allows the consuming component to subscribe to changes to the Context
< myContext. Provider value={set the value of the context required by the public component}>// Place components that require a common value
</MyContext.Provider>
Copy the code
instructions
value
Property value: Data value that is shared with the consuming componentProvider
的value
When the value changes, all the consuming components within it are rerenderedProvider
And its internalconsumer
Components are not subject toshouldComponentUpdate
Delta function, so whenconsumer
A component can be updated if its ancestor component exits the update
When value is an object, when the provider parent rerenders [value is given a new object], it may cause the consumer child to render unnecessarily
[Solution: You can raise the value to state.]
Class. ContextType [subscription context]
// Method 1:
class MyClass extends React.Component {
componentDidMount() {
let value = this.context;
/* After the component is mounted, use the value of the MyContext component to perform some side effects */
}
render() {
let value = this.context;
/* Render based on the value of the MyContext component */
}
}
MyClass.contextType = MyContext;
// Method 2: public class fields
class MyClass extends React.Component {
static contextType = MyContext;
render() {
let value = this.context;
/* Render based on this value */}}Copy the code
instructions
- will
React.createContext()
To create theContext
Object assigned toclass
的contextType
Property to subscribe tocontext
content - To subscribe to
context
Can be used in class componentsthis.context
In order to getProvider
Component defined invalue
Value to achieve some data sharing between components - Can be accessed in any lifecycle of a class component
this.context
- Subscribe to multiple
context
For example, seeThe official documentation
Context.Consumer subscribes to changes to the Context and updates the value in the Context object.
Set the shared context as an object that can contain methods to modify the value of the corresponding context
import { MyContext } from './theme-context';
function ThemeTogglerButton() {
The // Theme Toggler button not only gets the Theme value, it also gets a toggleTheme function from the context
return (
<MyContext.Consumer>
{({theme, toggleTheme}) => (
<button onClick={toggleTheme}
style={{backgroundColor: theme.background}}
>
Toggle Theme
</button>
)}
</MyContext.Consumer>
);
}
export default ThemeTogglerButton;
Copy the code
instructions
context
For the parent componentMyContext.Provider
The component’svalue
Attribute value [no need to re-subscribe]customer
The component accepts a function as its wrapper content with the corresponding function parametersprovider
The share set up in the componentvalue
Value for the corresponding element to render
Context.displayname [define MyContext to display the name in devTool]
Change the name of the corresponding element shown in the development tool review element by assigning a value to the Context’s property displayName
const MyContext = React.createContext(defaultValue);
MyContext.displayName = 'MyDisplayName';
<MyContext.Provider> // DevTools displays as "myDisplayName.provider"
<MyContext.Consumer> // DevTools displays "myDisplayName.consumer"
Copy the code
The use of Context in a function component
Use useContext to get context content information
// context.ts
const MyContext = React.createContext(defaultValue);
export default MyContext;
// App.tsx
const [state, setState] = useState({});
<MyContext.Provider value={state}>
<MyComponent />
</MyContext.Provider>
// MyComponent.tsx
import React, { useContext } from 'react';
import MyContext from './context';
const MyComponent = () = > {
// Display values with state and change values with setState
const { state, setState } = useContext(MyContext);
return (
/* Render work */)}export default MyComponent;
Copy the code
Used by the old Context API class component and function component
Outdated Context
// provider.tsx
class ContextProvider extends React.Component {
constructor(props) {
super(props);
this.state = { value: {}}}// When the state or props changes, getChildContext is called
getChildContext() {
const { value } = this.state;
return { value, changeValue };
}
// state value change function
changeValue = (value) = > {
this.setState({ value });
}
render() {
return (
<div>{this.props.children}</div>
)
}
}
ContextProvider.childContextTypes = {
value: PropTypes.object
};
// App.tsx
<ContextProvider>
<MyComponent />
</ContextProvider>
// Class child myComponent.tsx
class MyComponent extends React.Component {
static contextTypes = {
value: PropTypes.object
};
console.log(this.context); // { value: Object, changeValue: Function }
render() {
// Render}}// Function child myComponent.tsx
const MyComponent = (props, context) = > {
console.log(this.context); // { value: Object, changeValue: Function }
return (
// Render
)
}
MyComponent.contextTypes = {
value: PropTypes.object
};
Copy the code