-
[react] useRefreact+vue 2022. 9. 22. 14:56
- 태그의 속성을 동적으로 변경할 수 있는 방법
div태그 배경색 동적으로 변경하기
function App() { const myRef = useRef(null); return ( <div> <button onClick={() => { myRef.current.style.backgroundColor = "red" }}></button> <div ref={myRef}>박스</div> </div> ); } export default App;
- 태그 속성 ref에 정의한 useRef를 지정해준다.
- button을 클릭하면 useRef의 current속성의 style.backgroundColor에 색을 지정해 준다.
리스트로 뿌려준 값 속성 동적으로 변경하기
- 먼저 배열을 만들고 배열의 값을 뿌려준다
function App() { const myRef = useRef(null); const [list, setList] = useState([{ id: 1, name: "길동" }, { id: 2, name: "꺽정" }]); return ( <div> <button onClick={() => { myRef.current.style.backgroundColor = "red" }}></button> <div ref={myRef}>박스</div> {list.map((u,index) => (<h1 } >{u.name}</h1>))} </div> ); } export default App;
- useRef 배열 만들기
- Array.from({length:길이})로 원하는 길이의 빈 배열을 만들 수 있다.
- useRef 배열을 만들때는 createRef()함수를 반환시킨다.
const myRefs = Array.from({length:list.length}).map(()=>createRef());
- 색상을 저장한 배열 만들기
const colors = ['pink', 'gray', 'green', 'blue'];
- 색상 변경 버튼 만들기
<button onClick={() => { myRefs.forEach((m,index) => { m.current.style.backgroundColor=colors[index]})}}>색 변경</button>
- 적용 UI
'react+vue' 카테고리의 다른 글
[react] useEffect가 두 번 실행되는 현상 (0) 2022.09.23 [react] styled-components (0) 2022.09.23 [react] useMemo (0) 2022.09.22 [react] Too many re-renders. React limits the number of renders to prevent an infinite loop. (0) 2022.09.22 [javascript] import/export 방법 (0) 2022.09.21