티스토리 뷰

Study/react.js

[react]useRef 사용

빛장 2020. 1. 14. 17:27

리액트를 사용하여 해당 돔에 직접 접근해야할때

useRef 를 사용할 수 있다.

 

밑은 과격한 예시이다.

 

기존의 200px 검은 정사각형이 버튼을 누르면 300px 빨간색 정사각형으로 바꾸는 예제이다.

 

import React, { useRef } from "react"; //1. useRef 를 불러온다

const styled = {
  width: "200px",
  height: "200px",
  background: "black"
};

export default function App() {
  const handleChange = () => {
    colorChange.current.style = "width:300px; height:300px; background:red;"
    //4. 해당 ref 이름과 current 를이용해 직접 조정할 수 있다.
  };

  const colorChange = useRef(); //2. useRef 를 지정해준다.


//3. ref 를 이용해 지정한 useRef를 넣는다
  return (
    <>
      <div ref={colorChange} style={styled} />
      <button onClick={handleChange}>클릭</button>
    </>
  );
  
}

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함