RN

자식 컴포넌트에서 함수나 상태 끌어올리기

fullfish 2023. 12. 10. 23:45
// 자식 컴포넌트
import React, { useImperativeHandle, forwardRef } from 'react';

const ChildComponent = forwardRef((props, ref) => {
  useImperativeHandle(ref, () => ({
    childFunction() {
      console.log('자식 컴포넌트의 함수 실행됨');
      // 추가적인 로직
    }
  }));

  return (
    // 자식 컴포넌트의 JSX
    <div>자식 컴포넌트</div>
  );
});

export default ChildComponent;

 

// 부모컴포넌트
import React, { useRef } from 'react';
import ChildComponent from './ChildComponent';

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

  const handleButtonClick = () => {
    if (childRef.current) {
      childRef.current.childFunction();
    }
  };

  return (
    <div>
      <ChildComponent ref={childRef} />
      <button onClick={handleButtonClick}>자식 컴포넌트 함수 실행</button>
    </div>
  );
};

export default ParentComponent;