티스토리 뷰
리액트를 사용하여 해당 돔에 직접 접근해야할때
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>
</>
);
}
'Study > react.js' 카테고리의 다른 글
[warning]Use the `defaultValue` or `value` props on <select> instead of setting `selected` on <option>. (0) | 2020.01.27 |
---|---|
[노드패키지매니져]npm 과 npx 의 차이점 (0) | 2020.01.27 |
[react] 여러개의 인풋 관리 (0) | 2020.01.14 |
[react Hooks] use Input (0) | 2020.01.13 |
[react router]리액트 라우터 (0) | 2020.01.07 |
댓글