부모 컴포넌트에서 자식 컴포넌트 함수 호출하기
Post

부모 컴포넌트에서 자식 컴포넌트 함수 호출하기

useImperativeHandle 을 이용하여 부모 컴포넌트에서 자식 컴포넌트의 함수를 호출 할 수 있다.

Hooks API - React

Parent

1
2
3
4
5
6
7
8
9
10
11
12
13
import React, { useEffect, useState, useRef } from 'react';

const Parent = () => {
  const childRef = useRef();

  useEffect(() => {
    childRef.current.savePDF();
  }, []);

  return (
    <Child ref={childRef} />
  )
}

Child

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import React, { useEffect, useState, forwardRef, useImperativeHandle } from 'react';

const Child = forwardRef((props, ref) => {

  useImperativeHandle(ref, () => ({
    // 부모 컴포넌트에서 호출할 함수 선언
    savePDF
  }))

  const savePDF = () => {
    console.log('called savePDF!');
  }

  return (
    <div>Child</div>
  )
});