Reactから別のFunction Componentの関数を呼び出す:React Calling Function From Another Function Component


AfterBoxリストの関数を呼び出す方法をWeeklyBoxで探します.
useImperativeHandleというフィードバックフックで可能な方法を見つけた.
HomeのサブアイテムはWeeklyBoxList,AfterBoxListである.
このうちWeeklyBoxリストの子供はWeeklyBoxです.
以下に要約する.

Home.js
import React, {useRef} from "react";
import AfterBoxList from "../../components/Home/AfterBoxList";
import WeeklyBoxList from "../../components/Home/WeeklyBoxList";
import "./Home.css";

function Home() {
    const childRef = useRef(null);

    const refreshAfterBoxList = () => {
        childRef.current.getAfterBoxList();
    }

    return <div className = "home-layout">
            <div className = "home-layout__wrap">
                <div className = "home-layout__wrap__left">
                    <WeeklyBoxList 
                        refreshAfterBoxList = {refreshAfterBoxList}
                        />
                    <AfterBoxList 
                        ref = {childRef}
                        />
                </div>
            </div>
        </div>;
}

export default Home;
AfterBoxList.js
import React, { useImperativeHandle, useState, useEffect, forwardRef } from "react";
import axios from "axios";
import AfterBox from "./AfterBox";
import "./AfterBoxList.css";

export const AfterContext = React.createContext();

function AfterBoxList({accessToken, userId}, ref) {
   
   // 첫번째 방법
    useImperativeHandle(ref, () => ({
        getAfterBoxList
      }));

	// 두번째 방법
    // useImperativeHandle(ref, () => ({
    //     refreshAfterList: () => {
    //         getAfterBoxList();
    //     }
    //   }));

    async function getAfterBoxList() {
        // ...
    };

    return <div></div>;
}
export default forwardRef(AfterBoxList);
WeeklyBox.js
import React from "react";
import "./WeeklyBox.css";

function WeeklyBox({refreshAfterBoxList}) {
  
    const onClickCompleteBtn = () => {
        refreshAfterBoxList();
    }

    return <div className="weeklyBox">
    	...
	</div>;
}

export default WeeklyBox;
WeeklyBoxリストはHomeから受け取った関数をそのままサブWeeklyBoxに渡す.