πΒ Reference
π Chapter
β£
const ref = useRef(value)
useRef
λ₯Ό μ¬μ©νλ©΄ ref Obejctλ₯Ό λ°νν΄μ€λ€.//ref Object
{current: value}
// μμ
const ref = useRef("hi")
{current: "hi"}
const ref = useRef("hello")
{current: "hello"}
const ref = useRef("nice")
{current: "nice"}
current
λ‘ μ μ₯μ΄ λλ€.ref
Objectλ μμ μ΄ κ°λ₯νλ€.ref
λ μ»΄ν¬λνΈμ μ μμ μ£ΌκΈ° λμ μ μ§κ° λλ€. β μ»΄ν¬λνΈκ° κ³μν΄μ λ λλ§μ΄ λμ΄λ μ»΄ν¬λνΈκ° unmount
λκΈ° μ κΉμ§ κ°μ κ·Έλλ‘ μ μ§νλ€.useRef
λ κ°μ΄ λ³νν΄λ μ»΄ν¬λνΈλ₯Ό λλλ§ μν€μ§ μλλ€.
state
μ λΉμ·νκ² κ°μ μ μ₯νλ 곡κ°μ΄λ€.state
μ λ³ν β μ»΄ν¬λνΈ λλλ§ β μ»΄ν¬λνΈ λ΄λΆ λ³μλ€ μ΄κΈ°ν(리λλλ§ λ λλ§λ€, ν¨μν μ»΄ν¬λνΈκ° λ€μ νΈμΆλ¨.), Ref
μ κ°μ μ μ§λ¨.ref
μ λ³ν β No λλλ§ β λ³μλ€μ κ°μ΄ μ μ§λ¨.state
μ λ³ν β λλλ§ β κ·Έλλ ref
μ κ°μ μ μ§ λλ€.input μμμ focus()
λ₯Ό μ€ μ μλ€. β Document.querySelector()
component λ λλ§ μ μλμΌλ‘ input μ°½μ ν¬μ»€μ±μ΄ κ°κ² νλ κ²½μ°
const ref = useRef(value)
<input ref={ref} />
function App() {
const inputElement = useRef();
const focusInput = () => {
inputElement.current.focus();
};
return (
<>
<input type="text" ref={inputElement} />
<button onClick={focusInput}>Focus Input</button>
</>
);
}
ν¬μ»€μ€, ν μ€νΈ μ ν μμ, νΉμ λ―Έλμ΄μ μ¬μμ κ΄λ¦¬ν λ.
μ λλ©μ΄μ μ μ§μ μ μΌλ‘ μ€νμν¬ λ.
μλ νν° DOM λΌμ΄λΈλ¬λ¦¬λ₯Ό Reactμ κ°μ΄ μ¬μ©ν λ.