특정 DOM에 작업을 해야 할 때 ref를 사용한다.
즉, DOM을 꼭 직접적으로 건드려야 할때 ref를 사용하는 것이다
state를 사용하여 필요한 기능을 구현했지만, state만으로 해결할수 없는 기능들이 있다
input에 포커스 주기아래의 예시들은 모두 CLASS형 컴포넌트 일경우 적용 되는 것이다.
ref를 달고자 하는 요소에 ref라는 콜백 함수를 props로 전달해 주면 된다.
<input ref={ref=>{this.input=ref}}/>
this.input은 input 요소의 DOM을 가리킨다. ref의 이름은 원하는 대로 지정할수 있다.
리액트에 내장되어 있는 createRef 함수를 사용하는 것이다.
import React, { Component } from "react";
class RefTest extends Component {
input = React.createRef();
handleFocus = () => {
this.input.current.focus();
};
render() {
return (
<div>
<input ref={this.input} />
</div>
);
}
}
export default RefTest;
React.createRef()를 원하는 변수명에 담아 주어야 한다. 그리고 해당 멤버 변수를 ref를 달고자 하는 요소에 ref props로 넣어주면 적용된다.
<RefComponent ref={ ref => {RefComponent = ref}}/>
콜백함수를 이용해 ref를 설정해 주었다.
App.js

ScrollBox.js
