hooks
에서는 ref
를 사용할 수 없는데, 가능하게 해준 것이 바로 useRef
이다.
그리고, 자식 컴포넌트에서 ref
를 사용하기 위해선 useImperativeHandle
을 사용해야 한다. 사용 예시를 보자.
input
에 focus
를 준다.간단하게 코드만 정리해본다.
import React, {
useImperativeHandle,
forwardRef,
useRef,
} from "react";
const Component = forwardRef((props, ref) => {
const buttonRef = useRef();
useImperativeHandle(ref, () => ({
special: () => {
// console.log(buttonRef.current)
buttonRef.current.focus();
}
}));
return (
<div>
<input ref={buttonRef} placeholder="여기로 초점" value="123,000" />
<button onClick={props.onClick}>{props.children}</button>
</div>
);
});
const App = () => {
const btnRef = useRef();
const onFocus = () => {
btnRef.current.special();
}
return (
<div>
<Component ref={btnRef} onClick={onFocus} >
확인
</Component>
</div>
)
}
export default App;
App
은 부모 컴포넌트이고, Component
는 자식 컴포넌트이다.
부모에서 자식으로 btnRef
를 ref
로 넘겨주고, Component
는 props
와ref
를 받아온다. 이때, forwardRef
라는 것을 사용해야 ref
와 props
를 받아올 수 있다.
useImperativeHandle
를 사용해야 ref
를 다룰 수 있다.
useImperativeHandle
안에 special
을 선언한 것 처럼 만들어 준다. 그래야 App
컴포넌트 안에서 onFocus
함수 내부에 btnRef.current.special()
을 사용할 수 있다.
주석 처리한 console.log(buttonRef.current)
를 살려서 찍어보면,
위와 같이 나타나게 된다.