리액트로 뭐 만들 때
input창에 자동으로 focus 줘볼거임
모달창 띄우거나 뭐 그럴 때 알아서 포커스 가있으면
사용자들이 편해서 좋을듯
동적 방법과 정적 방법이 있다고 함
const Form = () => { const emailInput = useCallback((inputElement) => { if (inputElement) { inputElement.focus(); } }, []); return ( <form> <label> Email <input name="email" type="email" ref={emailInput} /> </label> <label> Password <input name="email" type="email" /> </label> <button type="submit">Login</button> </form> ); }; export default Form;
첫 번째는 useCallback() 훅을 쓰는거임
(작성중)
import React, { useRef, useEffect } from "react"; const Form = () => { const emailInput = useRef(null); useEffect(() => { if (emailInput.current) { emailInput.current.focus(); } }, []); return ( <form> <label> Email <input name="email" type="email" ref={emailInput} /> </label> <label> Password <input name="email" type="email" /> </label> <button type="submit">Login</button> </form> ); }; export default Form;
근데
The useEffect() Hook will tell React that you need your component to do something after it renders. It accepts two parameters. The first is the function that you want to run, and the second is a dependency array that functions the same as it did in useCallback().
The useRef() Hook does for functional components what createRef() did for class-based components. This Hook creates a plain JavaScript object that you can pass to an element to keep a reference of it. This reference can be accessed through the current property of the object.
그냥 태그에 autoFocus 주면 됨
(대소문자 구분)
근데 리액트 쓰면서 정적인 방법 쓰면 필요 없을듯