React explanation – parent component calls child component content [updating]

Time:2022-5-6

preface

This article belongs to react communication > parent-child communication > parent component calling child component.
Scenario of parent component calling child component:

  • Sub components are used in multiple places and need to be encapsulated separately
  • The logic of sub components is heavy, and the cost of using fully controlled mode is high

Using parent components to call child components for logical calls has the following advantages:

  • Sub components can be encapsulated and reused. And the logic inside is not disturbed by the outside world
  • More related logic can be encapsulated in sub components without passing props
  • Data collection is simple

text

Class Component

Hooks

Used hooks:useImperativeHandleanduseRef

/*Child subassembly*/
// https://reactjs.org/docs/hooks-reference.html#useimperativehandle
import {useState, useImperativeHandle} from 'react';
...
//The props subcomponent needs to accept Ref
const ChildComp = ({cRef}) => {
    const [val, setVal] = useState();
    //Note here that the first parameter of the useimperativehandle method is the ref reference of the target element
    useImperativeHandle(cRef, () => ({
        //Changeval is the method exposed to the parent component
        changeVal: (newVal) => {
          setVal(newVal);
        }
    }));
    ...
    return (
        <div>{val}</div>
    )
}
/*Fcomp parent component*/
import {useRef} from 'react;
...
const FComp = () => {
    const childRef = useRef();
    const updateChildState = () => {
        //Changeval is the method by which the child component is exposed to the parent component
        childRef.current.changeVal(99);
    }
    ...
    return (
        <>
            {/ * note here that you need to pass childref from the parent component to yourself through props attribute. CREF = {childref} * /}
            <ChildComp  cRef={childRef} />
            < button onclick = {updatechildstate} > trigger subcomponent method < / button >
        </>
    )
}

Method 2: refer to the official document of react:

import {useState, useImperativeHandle,forwardRef} from 'react';
//The props subcomponent needs to accept Ref
let ChildComp = (props,ref) => {
    //Note here that the first parameter of the useimperativehandle method is the ref reference of the target element
    useImperativeHandle(ref, () => ({
        //Changeval is the method exposed to the parent component
        changeVal: (newVal) => {
           
        }
    }));
    return (
        <div>{val}</div>
    )
}
ChildComp = forwardRef(ChildComp)
/*Fcomp parent component*/
import {useRef} from 'react';
const FComp = () => {
    const childRef = useRef();
    const updateChildState = () => {
        //Changeval is the method by which the child component is exposed to the parent component
        childRef.current.changeVal(99);
    }
    return (
        <>
            <ChildComp ref={childRef} />
            < button onclick = {updatechildstate} > trigger subcomponent method < / button >
        </>
    )
}

summary

demo:

  • props ref: https://codepen.io/specialCod…
  • forwardRef: https://codepen.io/specialCod…
  • common object: https://codepen.io/specialCod…
    Summary:
  • Can implement the parent component to call the child component method
  • Both props ref and forwardref are used to pass ref to subcomponents
  • Implementation requires arefObject (whyref? What are the characteristics [in fact, as long as an object is passed, ref should be related to the component life cycle]
  • Cannot read property ‘getList’ of undefined ( null in ref)
  • Implementation needsuseImperativeHandleIt plays the role of binding methods to objects
  • Assigning a value to ref.current is a side effect, so it is generally assigned to ref.current in the did function or event handling function;
  • The value of ref.current should be cleared when the component is unloaded.
    Essentially, useimperativehandle is helping us do these things.

todo:

  • Brief introduction to controlled communication mode

Recommended Today

Microsoft’s high-tech modular “tractor shed”

Microsoft has completed the construction of the primary stage of the Quincy data center in Washington, which is characterized by the infrastructure of plug and play for modular deployment, and the newly deployed cloud computing provides excellent flexibility. Quincy data center adopts a lightweight shape design, which is jokingly called “tractor shed” by Microsoft. Each […]