2

foreword

This article belongs to React Communication > Parent-Child Communication > Parent Component Calls Child Component.
Scenario of parent component calling child component:

  • Subcomponents are used in multiple places and need to be packaged separately
  • Subcomponent logic is heavier, and the cost of using fully controlled mode is higher

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

  • Subcomponents can be encapsulated and reused. And the logic inside is not disturbed by the outside world
  • More related logic can be encapsulated in subcomponents without passing props
  • Easy to collect data

text

Class Component

Hooks

Used hooks: useImperativeHandle and useRef

 /* child子组件 */
// https://reactjs.org/docs/hooks-reference.html#useimperativehandle
import {useState, useImperativeHandle} from 'react';
...
// props子组件中需要接受ref
const ChildComp = ({cRef}) => {
    const [val, setVal] = useState();
    // 此处注意useImperativeHandle方法的的第一个参数是目标元素的ref引用
    useImperativeHandle(cRef, () => ({
        // changeVal 就是暴露给父组件的方法
        changeVal: (newVal) => {
          setVal(newVal);
        }
    }));
    ...
    return (
        <div>{val}</div>
    )
}
 /* FComp 父组件 */
import {useRef} from 'react;
...
const FComp = () => {
    const childRef = useRef();
    const updateChildState = () => {
        // changeVal就是子组件暴露给父组件的方法
        childRef.current.changeVal(99);
    }
    ...
    return (
        <>
            {/* 此处注意需要将childRef通过props属性从父组件中传给自己 cRef={childRef} */}
            <ChildComp  cRef={childRef} />
            <button onClick={updateChildState}>触发子组件方法</button>
        </>
    )
}
  

Method 2, refer to the official react documentation:

 import {useState, useImperativeHandle,forwardRef} from 'react';
// props子组件中需要接受ref
let ChildComp = (props,ref) => {
    // 此处注意useImperativeHandle方法的的第一个参数是目标元素的ref引用
    useImperativeHandle(ref, () => ({
        // changeVal 就是暴露给父组件的方法
        changeVal: (newVal) => {
           
        }
    }));
    return (
        <div>{val}</div>
    )
}
ChildComp = forwardRef(ChildComp)
 /* FComp 父组件 */
import {useRef} from 'react';
const FComp = () => {
    const childRef = useRef();
    const updateChildState = () => {
        // changeVal就是子组件暴露给父组件的方法
        childRef.current.changeVal(99);
    }
    return (
        <>
            <ChildComp ref={childRef} />
            <button onClick={updateChildState}>触发子组件方法</button>
        </>
    )
}

Summarize

demo: https://codepen.io/collection/OLWOdO
Summarize:

  • The parent component can call the child component method
  • Both props ref and forwardRef are for passing ref to child components
  • The implementation needs a ref object (why is ref ? What is the feature?) [In fact, as long as an object is passed, ref should be related to the life cycle of the component]
  • Cannot read property 'getList' of undefined ( null in ref)
  • Implementation needs useImperativeHandle to bind methods to objects
  • Assigning a value to ref.current is a side effect, so generally assign a value to ref.current in the Did function or event handler;
  • The component needs to clean up the value of ref.current when it is unmounted.
    Essentially useImperativeHandle is doing these things for us.

todo:

  • A brief introduction to controlled communication

specialCoder
2.2k 声望168 粉丝

前端 设计 摄影 文学