본문 바로가기
WEB

리액트 ref react ref 사용법 예제 예시 No Rendering

by Ele(단단) 2023. 3. 21.
반응형

리액트 ref, react ref 사용법

특정 DOM 선택하기

- ref는 reference(참조)의 준말

 

current라는 프로퍼티를 가진 객체이며, DOM에 직접적인 접근이 가능

- focus, 텍스트 선택영역, 미디어 재생, 애니메이션 직접 실행 등 

 

LifeCycle상에서 componentDidMount 

- 라이프 사이클상에서 componentDidMount 이전에는 null이 current 프로퍼티에 담긴다

 

왜 DOM API가 아닌 ref를 사용하는가?

- ref는 특정 DOM 요소를 가져올 때 더 신뢰

- 라이프사이클에 따라 DOM 요소를 가져오지 못하는 경우가 있다

 

함수형 컴포넌트에서는 useRef를 사용

- createRef를 함수형에서 사용하면 ref 값이 초기화 되어 원하는 값을 얻지 못함

function TextInputWithFocusButton() {
  const inputEl = useRef(null);
  const onButtonClick = () => {
    // `current` points to the mounted text input element
    inputEl.current.focus();
  };
  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </>
  );
}

// console.log(inputEl.current.value)의 결과로 input 태그의 value 값을 확인 가능
반응형

댓글