반응형
리액트 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 값을 확인 가능
반응형
'WEB' 카테고리의 다른 글
버블링 막기 event.stopPropagation() 이벤트 (0) | 2023.03.21 |
---|---|
리액트 스크롤 상단으로 위치 시키기 리액트 라우터 (0) | 2023.03.15 |
JavaScript 기초 (0) | 2021.07.08 |
댓글