기본 활용
변수에 담아서 사용
createRef() 메소드로 변수 안에 useRef hook을 생성하고
map 함수로 리스트마다 useRef hook을 한 개씩 할당하는 방법
import React from "react";
export default function App() {
const values = [
{ id: 1, text: "hello world", refs: React.createRef() },
{ id: 2, text: "hello world", refs: React.createRef() },
{ id: 3, text: "hello world", refs: React.createRef() }
];
const clickHandler = (index) => {
console.log(values[index].refs.current);
};
return (
<div className="App">
{values.map((el, idx) => {
return (
<h1 key={idx.toString()} ref={el.refs}>
{el.id} {el.text}
</h1>
);
})}
<button onClick={() => clickHandler(0)}>refs 1</button>
<button onClick={() => clickHandler(1)}>refs 2</button>
<button onClick={() => clickHandler(2)}>refs 3</button>
</div>
);
}
react ref를 일반적인 변수 대신 useState, useRef, useMemo 등 다른 종류의 객체에 담을 수도 있음
const [values, setValues] = useState([
{ id: 1, text: "hello world", refs: React.createRef() },
{ id: 2, text: "hello world", refs: React.createRef() },
{ id: 3, text: "hello world", refs: React.createRef() }
]);
const values = useRef([
{ id: 1, text: "hello world", refs: React.createRef() },
{ id: 2, text: "hello world", refs: React.createRef() },
{ id: 3, text: "hello world", refs: React.createRef() }
]);
'React' 카테고리의 다른 글
React Hook useRef 메소드 사용하기 (0) | 2021.08.03 |
---|---|
React Hook이란? (0) | 2021.08.03 |
React-router <NavLink> 태그의 사용법 (0) | 2021.07.09 |