λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°

FA/React

20221001 React Hooks - useRef λ³€μˆ˜κ΄€λ¦¬, DOM μš”μ†Œ μ ‘κ·Ό

Hook의 κ·œμΉ™

  • React ν•¨μˆ˜ ꡬ성 μš”μ†Œ λ‚΄μ—μ„œλ§Œ ν˜ΈμΆœν•  수 있음(λ°˜λ“œμ‹œ Functional Component μ•ˆμ—μ„œ μ‚¬μš©ν•΄μ•Ό 함)
  • ꡬ성 μš”μ†Œμ˜ μ΅œμƒμœ„μ—μ„œλ§Œ ν˜ΈμΆœν•  수 있음
  • 쑰건문, 반볡문 μ•ˆμ—μ„œ λͺ» 씀

useRef

  • λ Œλ”λ§ 간에 값을 μœ μ§€
  • μ—…λ°μ΄νŠΈ μ‹œ λ‹€μ‹œ λ Œλ”λ§λ˜μ§€ μ•ŠλŠ” λ³€κ²½ κ°€λŠ₯ν•œ 값을 μ €μž₯ν•˜λŠ” 데 μ‚¬μš©
  • DOM μš”μ†Œμ— 직접 μ•‘μ„ΈμŠ€ν•˜λŠ” 데 μ‚¬μš©
//μƒμ„±ν•˜κ³  DOM λ…Έλ“œμ— μ—°κ²°ν•˜κΈ°
const ref = useRef();

// ...

return <div ref={ref}>λ ˆν”„λ ˆν”„</div>;




//DOM λ…Έλ“œ μ°Έμ‘°ν•˜κΈ°
const node = ref.current;
if (node) {
  // nodeλ₯Ό μ‚¬μš©ν•˜λŠ” μ½”λ“œ
}

 

λ³€ν™”λŠ” 감지해야 λ˜μ§€λ§Œ, κ·Έ λ³€ν™”κ°€ λ Œλ”λ§μ„ λ°œμƒμ‹œν‚€λ©΄ μ•ˆλ˜λŠ” 값을 λ‹€λ£° λ•Œ 편리

import { useState, useEffect, useRef } from "react";
import ReactDOM from "react-dom/client";

function App() {
  const [inputValue, setInputValue] = useState("");
  const count = useRef(0);

  useEffect(() => {
    count.current = count.current + 1;
  });

  return (
    <>
      <input
        type="text"
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
      />
      <h1>Render Count: {count.current}</h1>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

 

DOM μš”μ†Œμ— 직접 μ ‘κ·Ό κ°€λŠ₯

ex)  <input ret={ref}/> input μš”μ†Œμ— 포컀슀

Document.querySelector() λž‘ λΉ„μŠ·

import { useRef } from "react";
import ReactDOM from "react-dom/client";

function App() {
  const inputElement = useRef();

  const focusInput = () => {
    inputElement.current.focus();
  };

  return (
    <>
      <input type="text" ref={inputElement} />
      <button onClick={focusInput}>Focus Input</button>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

 

 

 

 

 

μ°Έκ³  및 μΆœμ €

https://ko.reactjs.org/docs/hooks-reference.html#useref

 

Hooks API Reference – React

A JavaScript library for building user interfaces

ko.reactjs.org

https://www.w3schools.com/react/react_useref.asp

 

React useRef Hook

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com