DOM을 꼭 직접적으로 건드려야 할 때
- 특정 input에 focus 주기
- 스크롤 박스 조작하기
- Canvas 요소에 그림그리기
<input ref={(ref) => {this.input = ref}} />
class RefSample extends Component {
input = React.createRef();
handleFocus = () => {
this.input.current.focus();
}
render() {
return(
<input ref={this.input} />
)
}
}
export default RefSample;
// App.jsx
class App extends Component {
render() {
return(
<>
<ScrollBox
ref={this.scrollBox = ref}
/>
/*
초기 렌더링시 this.scrollBox 값은 undefined
화살표 함수를 이용해 메서드를 실행하면
버튼을 누르는 시점에서 this.scrollBox.scrollBottom 값을 가져올 수 있음
*/
<button onClick={onClick={() => this.scrollBox.handleScroll()}}>맨 아래로</button>
</>
)
}
}
// ScrollBox.jsx
class ScrollBox extends Component {
scrollToBottom = () => {
const { scrollHeight, clientHeight } = this.box;
/* 앞 코드에는 비구조화 할당 문법을 사용했습니다.
다음 코드와 같은 의미입니다.
const scrollHeight = this.box.scrollHeight;
const clientHeight = this.box.cliengHeight;
*/
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: "650px",
background: "linear-gradient(white, black)",
};
return(
<>
<div style={style} ref={(ref) => this.box = ref}>
<div style={innerStyle}>
</div>
</div>
</>
)
}
}
Hook 함수의 useRef 메서드를 사용하여 Reaact.createRef 와 유사