React implements component data transfer through the useContext feature

Let’s talk about an attribute useContext
, which is really rarely used, but it’s still simple to do it.
Open our react project and create a folder components under src, because it is used between two or more components,
and then create two components under components. The two components are called dom.jsx dom1.jsx. The naming is not standardized, but it is just a case and I am too lazy to make it so standardized.

dom.jsx We write the code as the parent component as follows

import React from "react";
import Daom1 from "./dom1";

export const MyComponent = React.createContext();

const dom = () => {
    
    
  return (
    <div>
      <MyComponent.Provider value="hello dom1">
        <Daom1 />
      </MyComponent.Provider>
    </div>
  );
};

export default React.memo(dom);

Here we define a hello dom1 whose data value is a string type through vulue in MyComponent.Provider,
and then call our dom1 component as its own subcomponent

Then our dom1 code is written as follows

import React, {
    
     useContext } from "react";
import {
    
     MyComponent } from "./dom";

const Dom1 = () => {
    
    
  const contextValue = useContext(MyComponent);
  return (
    <div>
      <h1>{
    
    contextValue}</h1>
    </div>
  );
};

export default React.memo(Dom1);

Obtain the MyComponent object exported from the dom1 component in the same directory and output its value through useContext

Then call the dom.jsx component in the App root component.
The project running results are as follows.
insert image description here
You can see the value defined in dom MyComponent.Provider value and then get it in dom1 and display it in h1. It will be used less because there are many restrictions and I don’t know how to use it

Guess you like

Origin blog.csdn.net/weixin_45966674/article/details/131404209