
React에서 forwardRef()를 사용하는 방법은 무엇인가요?
React 앱에서 “함수 컴포넌트에는 ref를 제공할 수 없습니다. ref에 액세스하려고 시도하면 실패합니다. React.forwardRef()를 사용하려고 했습니까?”라는 오류 메시지를 만나면 걱정하지 마세요. forwardRef API는 useImperativeHandle 후크와 결합하여 사용자 정의 컴포넌트 내에서 ref를 어떻게 어디에 둘지를 사용자 정의할 수 있도록 해줍니다. forwardRef를 사용하여 사용자 지정 함수 컴포넌트에 ref를 전달할 수 있습니다.
React에서 Ref 이해하기
forwardRef의 사용법에 들어가기에 앞서, 다른 요소 유형에 대한 React에서 ref가 어떻게 작동하는지 간단히 알아보겠습니다:
일반 DOM 요소에서의 Refs
function AutoFocusInput() {
const inputRef = useRef(null);
useEffect(() => {
inputRef.current.focus();
}, []);
return <input ref={inputRef} />;
}
클래스 컴포넌트에서의 Refs
class Child extends Component {
state = { color: "red" };
toggleColor = () => {
this.setState({ color: this.state.color === "red" ? "blue" : "red" });
};
render() {
return
<div style={{ backgroundColor: this.state.color }}>yo</div>
;
}
}
class Parent extends Component {
childRef = createRef();
handleButtonClicked = () => {
this.childRef.current.toggleColor();
};
render() {
return (
<div>
<button onClick={this.handleButtonClicked}>색 변경!</button>
<Child ref={childRef} />
</div>
);
}
}
forwardRef를 사용하여 함수 컴포넌트에 Ref 전달하기
함수 컴포넌트에 ref를 전달해야 할 때는 forwardRef를 사용하면 됩니다. 단순히 ref를 DOM 요소에 전달하여 부모가 액세스할 수 있게 할 수 있습니다.
const RedInput = forwardRef((props, ref) => {
return <input style={{ color: "red" }} {...props} ref={ref} />;
});
function AutoFocusInput() {
const inputRef = useRef(null);
useEffect(() => {
inputRef.current.focus();
}, []);
return <RedInput ref={inputRef} />;
}
그러나 클래스 컴포넌트의 인스턴스와 유사한 방식으로 함수 또는 필드를 ref에 연결하려면 useImperativeHandle 후크를 사용할 수 있습니다:
const Child = forwardRef((props, ref) => {
const [color, setColor] = useState("red");
useImperativeHandle(ref, () => ({
toggleColor: () => setColor((prevColor) => (prevColor === "red" ? "blue" : "red")),
}));
return
<div style={{ backgroundColor: color }}>yo</div>
;
});
class Parent extends Component {
childRef = createRef();
handleButtonClicked = () => {
this.childRef.current.toggleColor();
};
render() {
return (
<div>
<button onClick={this.handleButtonClicked}>색 변경!</button>
<Child ref={childRef} />
</div>
);
}
}
결론
요약하면, forwardRef API를 사용하면 React에서 사용자 정의 함수 컴포넌트에 ref를 전달할 수 있습니다. forwardRef를 useImperativeHandle 후크와 함께 사용하여 ref가 어디에 배치되는지를 사용자 정의하고, 함수 또는 필드를 상위 컴포넌트에 노출시킬 수 있습니다. 다른 맥락에서의 ref의 세부 사항을 이해하면 React 컴포넌트의 리팩토링을 효과적으로 활용하고 문제를 해결하는 데 도움이 됩니다.