[React] child 컴포넌트에서 함수호출하기

vue Vnode처럼 react 사용해보기

Posted by lim.Chuck on October 22, 2024

[React]

  1. [React] vite React설치
  2. Project initial setting
  3. Hooks && Library
    1. [React] Javascript 파일을 Typescript Import해보자
    2. [React] react-router-dom 알아보고 사용하자
    3. [React] child 컴포넌트에서 함수호출하기
    4. [React] useCallback
    5. [React] framer-motion 알아보고 사용하자
    6. [React] Context API
    7. [React] react lazy 지연로딩 예제
    8. [React] react에서 캐싱처리를 위한 react queryd와 indexDB 비교분석
    9. [React] 스타일 라이브러리 styled-components stitches 비교
  4. [React] 프론트 에러추적 도구 Sentry 사용해보기
  5. [React] React 19 주요 변경점
  6. [React] DOM이란 무엇이고? 가상 DOM이란 무엇인가?
  7. [React] preact 알아보기

이슈

컴포넌트에서 함수를 만들고 사용할수있을까하는 의문이 생겼음 방법은다양하겠지만 context랑 provider사용할수도있고? 필자는 vue처럼 ref적용후 끌어와서 쓰고싶어졌음

사용방법

  1. Child구성 요소를 .으로 묶습니다 forwardRef.
  2. useImperativeHandle자식에 있는 후크를 사용하여 .에 함수를 추가합니다 Child.
  3. ref를 사용하여 부모에서 자식 함수를 호출합니다. ( 예: childRef.current.childFunction()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
//app.js
import { forwardRef, useImperativeHandle, useRef } from "react";

const Child = forwardRef((props, ref) => {
  useImperativeHandle(ref, () => ({
    childFunction1() {
      console.log("child function 1 called");
    },
    childFunction2() {
      console.log("child function 2 called");
    },
  }));

  return (
    <div>
      <h2>child content</h2>
    </div>
  );
});

export default function Parent() {
  const childRef = useRef(null);

  const handleClick = () => {
    childRef.current.childFunction1();

    childRef.current.childFunction2();
  };

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

      <h2>parent content</h2>

      <button onClick={handleClick}>Call child functions</button>
    </div>
  );
}

너무쉽다.

마무리

쉽게쓸수있고 컴포넌트 안에서만 사용한다면 좋은 훅일수있다고 생각한다