Ref


Ref(reference) ? 

HTML에서 id를 이용해서 DOM에 이름을 다는 것처럼 리액트 프로젝트 내부에서 DOM에 이름을 다는 개념입니다.


Ref를 사용하는 이유 ? 

ref는 DOM을 직접 건드려야 하는경우 사용합니다.

id를 사용할 수는 있지만, 같은 컴포넌트를 여러번 사용할 경우 유일해야하는 id가 중복이 발생 할 수 있습니다.


State로는 대체 불가능 한가?

아래와 같은 경우는 state만으로 해결이 불가능 합니다.

   1) 특정 <input>태그에 포커스를 주는 경우

   2) 스크롤 박스를 조작하는 경우

   3) <Canvas>태그에 그림을 그리는 경우


리액트에서 id는 사용 불가?

다른 라이브러리나 프레임워크를 사용할 경우 id를 꼭 사용해야만 하는 경우라면 중복 방지를 위해 뒤에 추가 텍스트를 붙여서 사용합니다.

예) button01, button02

 


Ref 사용 방법

props를 설정하는 방법과 유사하며 , ref 값으로 콜백 함수를 전달합니다.



<input ref="{(ref)=> {this.input.ref}}" />


Ref사용 예제(Scroll)


Ref를 이용해서 자식 컴포넌트인 ScrollBox의 스크롤을 아래, 위로 이동하는 예제입니다.


ScrollBox컴포넌트에서 <div>태그에 ref를 넘겨줍니다.


ScrollBox.js

import React, { Component } from 'react';

class ScrollBox extends Component {
scrollToChange =(param) =>{
const{scrollHeight, clientHeight} = this.box;
if(param==='d'){
this.box.scrollTop = scrollHeight - clientHeight;
}else{
this.box.scrollTop = 0;
}
}

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;


ScrollBox에서 box를 넘겨받은 후 ScrollBox에서 정의한 함수 scrollToChange() 함수를 사용할 수 있습니다.


App.js

import React, { Component } from 'react';
import './App.css';
import ScrollBox from './component/ScrollBox';

class App extends Component {
state = {
upDown : 'd'
,value : 'To Bottom'
}
updownChange =() =>{
if(this.state.upDown === 'd'){
this.setState({
upDown:'u'
,value : 'To Top'
});
}else{
this.setState({
upDown:'d'
,value : 'To Bottom'
});
}
};
render() {
return (
<div>
<ScrollBox ref={(ref)=>this.ScrollBox=ref}/>
<button
onClick={
()=>{
this.ScrollBox.scrollToChange(this.state.upDown);
this.updownChange();
}
}
>
{this.state.value}
</button>
</div>
);
}
}

export default App;


동작 결과


참고 : 리액트를 다루는 기술(저:VELOPERT)





'언어 > ReactJS' 카테고리의 다른 글

[React] 라이프 사이클 함수  (0) 2019.05.07
[React] 컴포넌트 반복  (0) 2019.05.05
[React] 이벤트 핸들링  (2) 2019.04.25
[React] State  (0) 2019.04.12
[React] Props  (1) 2019.04.11

+ Recent posts