리액트 forwardRef()

임찬수·2021년 11월 25일
0

Ref를 props로 넘겨 자식 컴포넌트에서 사용 할 수 있게하는 기능이다.

사용방법은 자식 컴포넌트의 함수를 forwardRef()로 감싸면 상위 Ref 객체를 props로 참조 할 수 있다.

import React, { forwardRef, useRef } from "react";

const Input = forwardRef((props, ref) => {
  return <input type="text" ref={ref} />;
});

function Login() {
  const inputRef = useRef(null);

  function handleFocus() {
    inputRef.current.focus();
  }

  return (
    <>
      <Input ref={inputRef} />
      <button onClick={handleFocus}>입력란 포커스</button>
    </>
  );
}
profile
프론트엔드 개발자가 되기 위한 정보를 정리합니다.

0개의 댓글

관련 채용 정보