본문 바로가기
React

[리액트] 부모 컴포넌트에서 자식 컴포넌트 함수 작동과 자식 컴포넌트에서 부모 컴포넌트 작동하는 법

by teamnova 2022. 9. 22.

리액트를 사용하다 보면 상위에 있는 컴포넌트 함수를 호출하거나 반대로 하위의 함수를 호출하고 싶을 때가 있습니다.

 

구조가 위와 같이 설계가 되었을 때

1) 부모 버튼을 눌렀을 때, 자식의 컴포넌트가 반응하고 싶거나

2) 자식 버튼을 눌렀을 때, 부모의 컴포넌트가 반응하고 싶을 경우

 

1) props를 이용합니다.

App.js

<Child parentFunction={parentFunction} />

Child.js

props.parentFunction();

원하는 함수(parentFunction)를 태그에 넣어 준 후,

자식 컴포넌트에서 props.parentFunction()으로 작동시킵니다.

2) useRef를 이용합니다.

App.js

const childRef = useRef(); 
childRef.current.childFunction();
 <Child ref={childRef}/>

Child.js

 import React, {useRef,forwardRef} from 'react'; 
const child = forwardRef((props, ref) =>{ 
 useImperativeHandle(ref, () => ({
      childFunction
   }));

}

전체 코드

App.js

import "./styles.css";
import Child from "../src/child";
import React, {useState, useEffect, useRef,forwardRef,useImperativeHandle} from 'react';


export default function App() {
  const [parentText, setparentText] = useState('부모 컴포넌트');
  const childRef = useRef();

  function parentFunction(){
    setparentText('부모 컴포넌트 함수 작동!!');
  }

  function childBtnEvent(){
    childRef.current.childFunction();
  }

  return (
    <div className="App" style={{border:"1px solid"}}>
      <h1>{parentText}</h1>
      <button onClick={childBtnEvent}> 자식 함수 작동하기 버튼</button>
      <Child parentFunction={parentFunction} ref={childRef}/>
    </div>
  );
}

child.js

import React, {useState, useEffect, useRef,forwardRef,useImperativeHandle} from 'react';
const child = forwardRef((props, ref) =>{
    const [childText, setChildText] = useState('자식 컴포넌트');

    useImperativeHandle(ref, () => ({
      childFunction
    }));

    function childFunction(){
      setChildText('자식 컴포넌트 함수 작동!!');
    }

    function childBtnEvent(){
      console.log("!!!!!!!!!");
      props.parentFunction();
    }

    return (
		<div style={{width:"80%",margin:"auto",border:"1px solid"}}>
      <p>{childText}</p>
      <button onClick={childBtnEvent}>부모 함수 작동하기 버튼</button>
		</div>
    );
});

export default child;