Component communication in React (react18) 03 - simply use Context to pass parameters deeply

1 Introduction

1.1 Other ways of component communication in React

1.2 Lead to Context

  • Demand scenario:
    • We know that if father passes on to son, props can be used, and if son passes on to grandson, props can also be used. However, if the family is large, the component relationship is like a big tree, passing it all the way down. If props are still used at this time, it will obviously be a problem. It seems a bit strenuous.
      • And if this parameter is not required, it is not very reasonable to pass it layer by layer through props.
      • Or, if the descendant is too far away from the root, if props are still used to pass it layer by layer, then passing props will become very tedious and inconvenient.
    • This requires considering how to skip the middle generation and still pass it on to subsequent generations? This requires the Context to be introduced next...
  • You can pass parameters deeply using Context, which can be used incomponent treemiddleNo props required to "pass" data "directly" into required components, see the official website introduction:
    Insert image description here
    Insert image description here

2. Simple example

  • Let’s first look at the effect of the implementation, as follows: the grandfather component sends a message to the grandson component:
    Insert image description here
  • Code design - directory structure
    Insert image description here
  • Code design - code implementation
    • context.js + App.js + index.js
      Insert image description here
    • Parent.jsx + Child.jsx + GrandSon.jsx
      Insert image description here

3. Grammar description

3.1 createContext(defaultValue)

  • as follows:
    Insert image description here

3.2 value

  • value: This value is what you want to pass to all components in this provider that read this context, no matter how deep they are. The value of context can be of any type. Components within this provider canGet the value of the nearest context provider above it by calling useContext(SomeContext)

3.3 useContext(SomeContext)

  • Call useContext at the top level of the component to read and subscribe to context.
    Insert image description here

4. Summary

4.1 Context

4.1.1 Context Summary

  • Context enables a component to provide information to the entire tree below it.
  • Method to pass Context:
    • export const MyContext = createContext(defaultValue)Create and export context via .
    • In any child component no matter how deep down the hierarchy, pass the context to useContext(MyContext)the Hook to read it.
    • Provide context by wrapping children in <MyContext.Provider value={...}> in the parent component.
  • Context will pass through any components in between.
  • Context allows you to write "more general" components.
  • Before using context, try passing props or passing JSX as children.

4.1.2 Context application scenarios

  • See the official website introduction:
    Insert image description here

4.1.3 Context-official website

4.2 createContext

  • Context enables components to pass information layer by layer without explicitly passing parameters.
  • existoutside of any componentCall createContext to create one or more contexts.
    Because, usually, components from different files will need to read the same context. Therefore, it has become common practice to define context in a separate file. You can use the export statement to export it for other files to read and use.
  • Refer to the official website:
    https://zh-hans.react.dev/reference/react/createContext#createcontext .

4.3 useContext()

  • If React doesn't find any provider for that particular context in the parent tree, the context value returned by useContext() will be equal to the default value you specified when creating the context;
  • createContext(defaultValue)Note that the default value of the call is only used if there is no matching provider at all . If there is <SomeContext.Provider value={undefined}>a component somewhere in the parent tree, seContext(SomeContext)the component calling u will receive undefinedthe value as context.
  • Refer to the official website:
    https://zh-hans.react.dev/reference/react/useContext .

5. Attached code

  • context.js

    /**
     * 1. 通常,来自不同文件的组件都会需要读取同一个 context。
     * 2. 因此,在一个单独的文件内定义 context 便成了常见做法。
     * 3. 你可以使用 export 语句 将其导出,以便其他文件读取使用
     */
    import {
          
           createContext } from "react";
    
    const MessegeContext = createContext();
    
    export default MessegeContext;
    
    
    // import { createContext } from 'react';
    
    // export const ThemeContext = createContext('light');
    // export const AuthContext = createContext(null);
    
  • Parent.jsx

    import React from "react";
    import Child from "./Child";
    import './index.css'
    import {
          
           useState } from "react";
    import MessegeContext from "./context.js";
    
    
    function Parent() {
          
          
        const [notice, setNotice] = useState('孙子,你真棒!!');
    
        return(
    
            // <div className="parent">
            //     我是父组件!
    
            //     <div className="child">
            //         <Child notice={'通知——今天放假!'}/>
            //     </div>
            // </div>
    
            // 这里的属性,只能用 value
            <MessegeContext.Provider value={
          
          notice}>
                <div className="parent">
                    我是父组件!
    
                    <div className="child">
                        <Child notice={
          
          '通知——今天放假!'}/>
                    </div>
                </div>
            </MessegeContext.Provider>
    
        )
    }
    
    export default Parent;
    
  • Child.jsx

    import React from "react";
    import GrandSon from "./GrandSon";
    import './index.css'
    
    function Child(props){
          
          
    
        return(
            <div>
                我是子组件!!!
                <br /><br />
                收到来自于父组件的数据:{
          
          props.notice}
    
                <br /><br />
                <div className="grandSon">
                    <GrandSon />
                </div>
               
            </div>
        )
    }
    
    export default Child;
    
  • GrandSon.jsx

    import {
          
           useContext } from "react"
    import MessegeContext from "./context.js";
    
    export default function GrandSon(){
          
          
    
        // 在组件的顶层调用 useContext 来读取和订阅 context。
        const msgContent = useContext(MessegeContext);
        
        console.log(msgContent);
        
        return(
            <div>
                我是孙组件!!
    
                <br />
                我收到爷爷的信息是:{
          
          msgContent}
    
            </div>
        )
    }
    
  • componenet–>index.css

    .parent{
        background-color: blueviolet;
        border: 1px solid;
        height: 900px;
        width: 600px;
        text-align: center;
    }
    
    .child{
        background-color: green;
        height: 300px;
        margin: 20px;
    }
    
    .grandSon{
        background-color: grey;
        height: 150px;
        margin: 20px;
    }
    

Guess you like

Origin blog.csdn.net/suixinfeixiangfei/article/details/133038359