See the React website for Context

Context provides a way to pass data across the component tree without manually adding props for each layer of components. In a typical React application, data is passed top-down (from parent to child) through the props properties, but this is extremely cumbersome for certain types of properties (e.g. locale preferences, UI themes) that are required by many components in the application. Context provides a way to share such values between components without explicitly passing props layer by layer through the component tree.

Context provides a local global scope. Using Context eliminates the need to manually pass props layer by layer.

This article mainly introduces three ways to use Context:

  1. React.createContextTo provide theProviderandConsumer
  2. Function components:React.createContextTo provide theProvideranduseContexthook
  3. The Class components:React.createContextTo provide theProviderandclassthecontextTypeattribute

The first is the Provider and Consumer provided by React. CreateContext

Write the basic environment conditions for using the Context, and the rest of the code will be based on that environment

// Create a file, tentatively named context.js, that exports the return value of createContext()
import { createContext } from "react";

export default createContext();
Copy the code

In the root component app.jsx, import the context written above and wrap it with the Provider component provided by the context to define the local global scope. After passing the value, it can be provided to child components for consumption

When a Provider’s value changes, all of its internal consuming components are rerendered. Both the Provider and its internal consumer component are not subject to the shouldComponentUpdate function, so the consumer component can update if its ancestor exits updating.

import React, { createContext } from "react";
import MyContext from "./context";

import GeneralC from "./GeneralC";
import FnC from "./FnC";
import ClassC from "./ClassC";

export default function App() {
  return (
    // The Provider component receives a value attribute, where it passes in an object with the name attribute
    <MyContext.Provider value={{ name: `context's value is string! `}} >}}}}}}}}}}}}}}}}}}}}}}}}}}<GeneralC/>
      <hr/>
      <FnC/>
      <hr/>
      <ClassC/>
    </MyContext.Provider>
  );
}
Copy the code

In the GeneralC component, importing the context and using its supplied Consumer component to subscribe to changes to the context requires a function as a child element. The first parameter of the function is the value provided by the Provider component

import React, { useReducer } from "react";
import MyContext from "./context";

const GeneralC = () = > {
  return (
    //
    <MyContext.Consumer>
      {(value) => {
        return (
          <div>{json.stringify (value)}</div>
        );
      }}
    </MyContext.Consumer>
  );
};

export default GeneralC;
Copy the code

A value in JSON format should appear on the page

Second: function components: React.createContext provides the Provider and useContext hooks

Import the useContext hook function, which receives the value returned by createContext() as the current value of the context. The current context value is the value of < myContext.provider > from the upper-layer component closest to the current component Prop the decision.

import React, { useContext } from "react";
import MyContext from "./context";

const FnC = () = > {
  const context = useContext(MyContext);
  return <div>{json.stringify (Context)}</div>;
};

export default FnC;
Copy the code

Two VALUES in JSON format should appear on the page

Class component: React.createContext provides the Provider and Class contextType properties

The contextType property mounted on the class is reassigned to a Context object created by react.createcontext (). This allows you to use this.context to consume the value of the most recent context. You can access it in any lifecycle, including the Render function.

Using the static keyword to add static attributes is the same as adding attributes directly to a class. It will end up being added to the class, not the instance of the class

import React, { Component } from "react";
import context from "./context";

class ClassC extends Component {
  static contextType = context;
  render() {
    const value = this.context;
    return <div>} {json.stringify (value)}</div>; }}// ClassC.contextType = context; // This is the same as the static keyword
export default ClassC;
Copy the code

Three values in JSON format should appear on the page

If you can read the Context, you can write the Context, so let me rewrite the code.

Changing the context in the app.js component simply calls the component’s own setStore function

import React, { useState } from "react";
// Import the useState hook.const value = {
  name: `context's value is string! `
};

export default function App() {
  const [store, setStore] = useState(value);
  // Instead of passing a simple object, the Provider's value is passed as the key/value of the new object, and the child component can call the App's setStore function to update it
  return (
    <MyContext.Provider value={{ store.setStore}} >{/* Change Context in parent component */}<button
        onClick={()= >{ setStore({ name: "App change value!" }); }} > change context for App</button>{/* Here is the component introduced, omitted... * /}</MyContext.Provider>
  );
}
Copy the code

A button should appear on the page. ClickThe App...The button,storeUpdated toApp change value!To subscribe tocontextCan be updated to the latest value

The FnC component is used to update the context. The original code does not need to be changed. A button is added to call the setStore function passed by the context

import React, { useContext } from "react";
import MyContext from "./context";

const Component = () = > {
  const context = useContext(MyContext);
  return (
    <div>{json.stringify (Context)}<button
        onClick={()= >{ context.setStore({ name: "FnC change value!" }); }} > Change context for the FnC child</button>
    </div>
  );
};

export default Component;
Copy the code

Another button should now appear on the page. ClickAs FnC...The button,storeUpdated toFnC change value!, the effect and inAppThe changes in the component are consistent, so the component is updatedcontextThe ability to

There are three ways to use a Context in React. See the React documentation for more informationContextThe introduction of