React
ref를 prop으로 넘기기( forWardRef)
sorarar
2023. 3. 10. 22:24
320x100
반응형
Ref와 DOM
Ref는 render메서드에서 생성된 DOM 노드나 React 엘리먼트에 접근하는 방법을 제공
React에서 일반적으로 사용할 수 없는 prop이 몇 가지 있다, ref prop도 HTML Element 접근이라는 특수한 용도로 사용되기 때문에 일반적인 prop으로 사용할 수 없다
=> 함수 컴포넌트는 인스턴스가 없기 때문에
부모 컴포넌트에서 forwardRef 함수를 사용하여 자식 컴포넌트로 ref를 전달할 수 있다
react.forwardRef
- 렌더링에 사용될 함수를 일자로 받고 React는 이 함수를 props와 ref을 사용하여 호출 함수는 React 노드를 반환한다
<Input/> 컴포넌트에 forwardRef()라는 함수를 적용
import React, { forwardRef } from 'react';
const Input = forwardRef((props, ref) => {
return (
<input type="text" ref={ref} />
);
});
const Form = () => {
const inputRef = useRef(null);
const handleSubmit = (event) => {
event.preventDefault();
console.log(inputRef.current.value);
};
return (
<form onSubmit={handleSubmit}>
<Input ref={inputRef} />
<button type="submit">Submit</button>
</form>
);
};
728x90
반응형