The use of Context in React, passing values across components

What is Context?

Context provides a way to pass data between component trees without manually adding props to each layer of components. A bit like Vuex
in a typical React application, data is passed from top to bottom (from parent to child) through props attributes, but this approach is cumbersome for some scenarios, Context provides a way
to A way to share such values ​​between components without passing props layer by layer through the component tree.

use context

Custom Context
src/store/testContext.js

*   Context相当于一个公共的存储空间,
*       我们可以将多个组件中都需要访问的数据统一存储到一个Context中,
*       这样无需通过props逐层传递,即可使组件访问到这些数据
*   通过React.createContext()创建context
import React from 'react';

const TestContext = React.createContext({
    
    
    name:'孙悟空',
    age:18
});
export default TestContext;

Use one

1. Introduce context
2. Use the Xxx.Consumer component to create
the tag body of the element Consumer needs a callback function,
which will set the context as a parameter of the callback function, through which the data stored in the context can be accessed

A.js (render to page)

import React from "react";
import TestContext from "../store/testContext";
export default function A() {
    
    
  return (
    <div>
      我是A组件
      <TestContext.Consumer>
        {
    
    (ctx) => {
    
    
          return (
            <div>
              {
    
    ctx.name}-{
    
    ctx.age}
            </div>
          );
        }}
      </TestContext.Consumer>
    </div>
  );
}

insert image description here

Use method two

1. Import Context
2. Use the hook function useContext() to get the context
useContext() needs a Context as a parameter,
it will get the data in the Context and return it as the return value

import React, {
    
     useContext } from "react";
import TestContext from "../store/testContext";
export default function A() {
    
    
  const ctx = useContext(TestContext);
  return (
    <div>
      {
    
    ctx.name} -- {
    
    ctx.age}
    </div>
  );
}

insert image description here

Xxx.Provider officially uses the data in Context

- 表示数据的生产者,可以使用它来指定Context中的数据
- 通过value来指定Context中存储的数据,
这样一来,在该组件的所有的子组件中都可以通过Context来访问它所指定数据

当我们通过Context访问数据时,他会读取离他最近的Provider中的数据,
 如果没有Provider,则读取Context中的默认数据

app.js

import TestContext from "../src/store/testContext";
export default function App() {
    
    
 return (
  <div>
 <TestContext.Provider value={
    
    {
    
     name: "猪八戒", age: 28 }}>  这里value的内容才是Context真正的内容,
        <A></A>                                              达到组件数据共享
 </TestContext.Provider>
  </div>
)
}

insert image description here

Context explanation link

Guess you like

Origin blog.csdn.net/z18237613052/article/details/129956346
Recommended