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
'FA > React' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
20221006 react JSXμμ forμ€λ₯ (0) | 2022.10.06 |
---|---|
20221005 React Hooks - useContext (0) | 2022.10.05 |
20220928 Reactμμ μΈμ€ν μ€ν 리μ²λΌ νκΈ° (0) | 2022.09.28 |
20220927 Reactμμ sweetalert2 μ¬μ©νκΈ° (0) | 2022.09.27 |
22020926 React Hooks - useState, useEffect (0) | 2022.09.26 |