FrontEnd
[React] ref
mingg123
2021. 1. 18. 23:28
ref 를 이용하면 돔 요소에 직접 접근 할 수 있다.
돔 요소에 포커스를 주거나, 크기나 스크롤 위치를 알고 싶을 경우
함수형 컴포넌트에서 ref 속성값을 사용한 예
import React, { useRef, useEffect } from "react";
function TextInput({ inputRef }) {
return (
<div>
<input type="text" ref={inputRef} />
<button>저장</button>
</div>
);
}
export default function Form() {
const inputRef = useRef();
useEffect(() => {
inputRef.current.focus();
}, []);
return (
<div>
<TextInput inputRef={inputRef} />
<button onClick={() => inputRef.current.focus()}>텍스트로 이동</button>
</div>
);
}
forwardRef 함수를 사용하는 코드
import React, { useRef, useEffect } from "react";
const TextInput = React.forwardRef((props, ref) => (
<div>
<input type="text" ref={ref} />
<button>저장</button>
</div>
));
export default function Form() {
const inputRef = useRef();
useEffect(() => {
inputRef.current.focus();
}, []);
return (
<div>
<TextInput ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>텍스트로 이동</button>
</div>
);
}
forwardRef 를 사용하면 부모 컴포넌트에서 넘어온 ref 속성값을 직접 처리할 수 있다.
이전에는 inputRef로 사용했던 이름을 ref로 사용할 수 있게 됨.
useRef훅으로 만들어진 ref객체를 ref 속성값에 연결하는 경우를 살펴봄.