티스토리 뷰

 forwardRef는 부모 컴포넌트에서 자식 컴포넌트의 ref에 직접 접근할 수 있도록 해주는 기능이다.
여기에 useImperativeHandle을 같이 쓰면, 단순히 DOM 접근뿐 아니라 자식의 특정 메서드나 값을 부모에서 직접 호출할 수 있게 된다.


◎App.tsx

import React, {useRef} from 'react';
import {Button, View} from 'react-native';
import ChildComponent, {ChildRefType} from './ChildComponent';

const App = () => {
  const childRef = useRef<ChildRefType>(null);

  const onPress = () => {
    // 자식에서 정의한 메서드 호출
    childRef.current?.focusInput();
  };

  return (
    <View style={{marginTop: 50}}>
      <Button title="Focus Child Input" onPress={onPress} />
      <ChildComponent ref={childRef} />
    </View>
  );
};

export default App;

◎ChildComponent.tsx

import React, {forwardRef, useImperativeHandle, useRef} from 'react';
import {TextInput} from 'react-native';

export type ChildRefType = {
  focusInput: () => void;
};

const ChildComponent = forwardRef<ChildRefType>((props, ref) => {
  const inputRef = useRef<TextInput>(null);

  useImperativeHandle(ref, () => ({
    focusInput: () => {
      inputRef.current?.focus();
    },
  }));

  return <TextInput ref={inputRef} style={{borderWidth: 1, padding: 8}} />;
});

export default ChildComponent;

 

 위 코드에서 ChildComponent는 forwardRef로 부모로부터 ref를 전달받고,
useImperativeHandle로 그 ref 안에 focusInput 메서드를 노출했다.
부모에서는 childRef.current.focusInput()을 호출하면 내부 TextInput이 포커스된다.

 

 forwardRef와 useImperativeHandle을 이렇게 조합하면,
상위 컴포넌트에서 하위 컴포넌트의 특정 기능을 바로 호출할 수 있고,
네비게이션이나 상태 변화 없이도 화면 제어가 가능하다.

 

navigationProp, propsList 같은 타입 정의가 처음엔 귀찮아 보여도,
익숙해지면 유지보수와 코드 안정성에서 큰 이득을 준다.

 

끝!

반응형
Comments