티스토리 뷰
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 같은 타입 정의가 처음엔 귀찮아 보여도,
익숙해지면 유지보수와 코드 안정성에서 큰 이득을 준다.
끝!
반응형
'Mobile > react-native' 카테고리의 다른 글
| [React Native] 블루투스 온도계 연동하기 (feat. 패킷 스니핑) (1) | 2025.11.24 |
|---|---|
| [react-native] typescript 환경에서 navigation 사용 (0) | 2024.02.21 |
| [react-native] typescript로 Context API 사용 예제 (0) | 2024.02.21 |
| [react-native] typescript 환경에서 Hooks 예제 (1) | 2024.02.20 |
| [react-native] typescript환경에서 Props 사용 (0) | 2024.02.20 |
Comments
최근에 올라온 글
최근에 달린 댓글
TAG
- AsyncStorage
- 인천 구월동 이탈리안 맛집
- 맛집
- react-native
- 인천 구월동 맛집
- 파니노구스토
- redux-thunk
- react
- Promise
- redux
- 이탈리안 레스토랑
- Async
- javascript
- await
- 정보보안기사 #실기 #정리
- Total
- Today
- Yesterday