클래스형 컴포넌트에서 ref를 사용하는 방법
- 함수 컴포넌트에서 ref를 사용하려면 Hooks를 사용해야 함
리액트에서 잘 사용하는 문법은 아니라 간략히 정리
DOM을 꼭 사용해야하는 상황
- 특정 input에 포커스 주기
- 스크롤 박스 조작하기
- Canvas 요소에 그림 그리기
ref 사용
1. 콜백 함수 사용
- ref를 달고자 하는 요소에 ref라는 콜백 함수를 props로 전달
- 이 콜백 함수는 ref 값을 파라미터로 전달 받음
- 그리고 함수 내부에서 파라미터로 받은 ref를 컴포넌트의 멤버 변수로 설정
<input ref = {(ref) => {this.input = ref}} />
2. createRef 사용
- 더 적은 코드로 쉽게 사용가능
- 리액트 v16.3부터 도입
import React, { Component } from "react";
class createRef extends Component {
input = React.createRef();
handleFocus = () => {
this.input.current.focus();
};
render() {
return (
<div>
<input ref={this.input} />
</div>
);
}
}
export default createRef;
컴포넌트에 ref 달기
<MyComponent
ref = {(ref) => {this.myComponent = ref}} />
- 이렇게 하면 MyComponent 내부의 메서드 및 멤버 변수에도 접근 가능
컴포넌트에 메서드 생성 → 컴포넌트에 ref 달고 내부 메서드 사용
// ScrollBox.js
import { Component } from 'react';
class ScrollBox extends Component {
scrollToBottom = () => {
const { scrollHeight, clientHeight } = this.box;
this.box.scrollTop = scrollHeight - clientHeight;
};
render() {
(...)
}
}
export default ScrollBox;
// App.js
import React, { Component } from "react";
import ScrollBox from "./ref/ScrollBox";
class App extends Component {
render() {
return (
<div>
<ScrollBox ref={(ref) => (this.scrollBox = ref)} />
<button onClick={() => this.scrollBox.scrollToBottom()}>맨 밑으로</button>
</div>
);
}
}
export default App;
'React' 카테고리의 다른 글
[React] 컴포넌트의 라이프사이클 메서드 (0) | 2023.03.23 |
---|---|
[React] 컴포넌트 반복 (0) | 2023.03.21 |
[React] 이벤트 핸들링 (0) | 2023.03.16 |
[React] 컴포넌트 (0) | 2023.03.16 |
[React] Virtual DOM (0) | 2023.01.16 |