리액트에서 태그를 특정화하는데 id대신 ref를 사용해야함. 같은 컴포넌트를 여러 번 사용할 때 중복id가 가진 DOM이 발생하기 때문
5.1 ref는 어떤 상황에서 사용해야 할까?
- DOM을 꼭 직접적으로 건드려야 할 때
- DOM을 꼭 사용해야 하는 상황
- 특정 input에 포커스 주기
- 스크롤 박스 조작하기
- Canvas 요소에 그림 그리기 등
5.2 ref 사용
5.2.1 콜백 함수를 통한 ref 설정
//ref를 달고자 하는 요소에 ref라는 콜백 함수를 props로 전달. 이 콜백 함수는 ref값을 파라미터로 전달받음.
//함수 내부에서 파라미터로 받은 ref를 컴포넌트의 멤버 변수로 설정. this.input은 input 요소의 DOM을 가리킴.(ref이름 자유 지정)
<input ref={(ref)=>{this.input=ref}}/>
5.2.2 createRef를 통한 ref 설정
리액트에 내장되어 있는 createRef함수를 사용하면 더 적은 코드로 ref를 쉽게 사용할 수 있음. (v16.3부터 도입)
import React, {Component} from "react";
class RefSample extends Component {
input = React.createRef();
handleFocus = () => {
this.input.current.focus();
}
render() {
return (
<div>
<input ref={this.input}/>
</div>
)
}
}
export default RefSample;
5.3 컴포넌트에 ref 달기
component에도 ref를 달 수 있음. (DOM과 방법 동일).
내부의 ref(메서드 및 멤버 변수)에도 접근할 수 있게 됨.
- 스크롤 박스를 아래로 내리는 예시
//App.js
import React, {Component} from 'react';
import ScrollBox from "./ScrollBox";
class App extends Component {
render() {
return (
<div>
<ScrollBox ref={(ref) => this.scrollBox = ref}/>
<button onClick={()=>this.scrollBox.scrollToBottom()}>
맨 밑으로
</button>
</div>
);
}
}
export default App;
//ScrollBox.js
import React, {Component} from "react";
class ScrollBox extends Component {
scrollToBottom = () => {
const {scrollHeight, clientHeight} = this.box;
this.box.scrollTop = scrollHeight - clientHeight;
}
render() {
const style = {
border: '1px solid black',
height: '300px',
width: '300px',
overflow: 'auto',
position: 'relative'
}
const innerStyle = {
width: '100%',
height: '500px',
background: 'linear-gradient(white, black)'
}
return (
<div style={style} ref={(ref) => {
this.box = ref
}}>
<div style={innerStyle}/>
</div>
);
}
}
export default ScrollBox;
'개발 도서 > 리액트를 다루는 기술(개정판)' 카테고리의 다른 글
7장 컴포넌트의 라이프사이클 메서드 (0) | 2020.05.23 |
---|---|
6장 컴포넌트 반복 (0) | 2020.05.23 |
4장 이벤트 핸들링 (0) | 2020.05.22 |
3장 컴포넌트 (0) | 2020.05.17 |
2장 JSX (0) | 2020.05.16 |