useState
useRef
import React, { useRef } from "react";
function MyComponent() {
// useRef를 사용하여 참조 객체 생성
const myInputRef = useRef<HTMLInputElement>(null);
const focusInput = () => {
// current 프로퍼티를 통해 input 요소에 접근
if (myInputRef.**current**) {
myInputRef.current.focus(); // input 요소에 포커스 설정
}
};
return (
<div>
**<input ref={myInputRef} type="text" /> // input 요소에 useRef 지정**
<button onClick={focusInput}>Focus Input</button>
</div>
);
}
// 사용 예시
function App() {
return (
<div>
<MyComponent></MyComponent>
</div>
);
}
export default App;
useState vs. useRef
forwardRef
useImperativeHandle