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;

'RN' 카테고리의 다른 글

대진표 예시  (0) 2023.12.11
기본적인 모달  (0) 2023.12.10
stack 넘어갈때 화면 번쩍임 해결(흰화면)  (0) 2023.12.08
FlatList 격자형태로 이쁘게 나열하기  (0) 2023.12.08
style 따로 빼서 쓰기  (0) 2023.12.07