Ref 사용하는 이유
Ref는 리액트 에서 DOM 요소에 직접 접근 할수 있도록 제공되는 기능으로
useState와 비슷하지만 차이점이 존재한다.
Ref는 값을 변경시키지만 렌더링이 되지 않는다
즉 렌더링을 하고싶지 않은데 내부값을 수정하고 싶을때 사용한다
예시코드
import React, { useRef } from 'react';
const FocusInput = () => {
const inputRef = useRef(null); // ref 생성
const handleFocus = () => {
inputRef.current.focus(); // input 요소에 포커스
};
const handleAlert = () => {
alert(`입력된 값: ${inputRef.current.value}`); // 입력 값 읽기
};
return (
<div>
<input ref={inputRef} type="text" placeholder="여기에 입력하세요" />
<button onClick={handleFocus}>포커스 설정</button>
<button onClick={handleAlert}>값 확인</button>
</div>
);
};
export default FocusInput;
상위 컴퍼넌트에서 하위 컴퍼넌트 ref값을 얻고 싶다면?
상위컴퍼넌트
import React, { useRef } from 'react';
import ChildComponent from './ChildComponent';
const ParentComponent = () => {
const childInputRef = useRef(null); // 하위 컴포넌트의 ref
const handleFocus = () => {
childInputRef.current.focus(); // 하위 컴포넌트의 input에 포커스
alert(`입력된 값: ${childInputRef.current.value}`); // 입력 값 읽기
};
return (
<div>
<ChildComponent ref={childInputRef} />
<button onClick={handleFocus}>하위 입력 필드에 포커스</button>
</div>
);
};
export default ParentComponent;
하위컴퍼넌트
import React, { forwardRef } from 'react';
const ChildComponent = forwardRef((props, ref) => {
return (
<div>
<input ref={ref} type='text'/>
</div>
);
});
export default ChildComponent;
반응형
'html,css,js 공부 > React' 카테고리의 다른 글
리액트 기존 리덕스 사용방법 (0) | 2024.12.13 |
---|---|
리액트 라우터 사용법 (1) | 2024.12.08 |
리액트 props 사용법 (1) | 2024.11.23 |
리액트 Global State (0) | 2024.03.23 |
React 메모이제이션 (0) | 2024.03.20 |