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>
</>
);
}