5장 ref: DOM에 이름 달기
일반 HTML에서 DOM 요소에 이름을 달 때는 id를 사용합니다.
<div id="my-element"></div>
이렇게 HTML에서 id를 사용하여 DOM에 이름을 다는 것처럼 리액트 프로젝트 내부에서 DOM에 이름을 다는 방법이 있습니다. 바로 ref 개념입니다.
5.1 ref는 어떤 상황에서 사용해야 할까?
✅ DOM을 꼭 직절적으로 건드려야 할 때
5.1.3 DOM을 꼭 사용해야 하는 상황
- 특정 input에 포커스 주기
- 스크롤 박스 조작하기
- Canvas 요소에 그림 그리기 등
5.2.3.1 input에 ref 달기
handleButton = () => {
this.setState({
clicked: true,
validated: this.state.password === "0000",
});
this.superMan.focus();
};
render() {
return (
<div>
<input
ref={(ref)=>this.superMan = ref}
(...)
/>
<button onClick={this.handleButton}>검증</button>
</div>
);
}
5.3 컴포넌트에 ref 달기
<MyComponent
ref={(ref)=>{this.myComponent = ref}}
/>
이렇게 하면 MyComponent 내부의 메서드 및 멤버 변수에도 접 글 할 수 있습니다.
즉, 내부의 ref에도 접근할 수 있습니다.(예: myComponent.handleButton, myComponent.input 등).
5.3.2.2 App 컴포넌트에서 스크롤 박스 컴포넌트 렌더링
ScrollBox.js
import React, { Component } from "react";
export default class ScrollBox extends Component {
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>
);
}
}
import { Component } from "react";
import "./App.css";
import ScrollBox from "./exercise/ScrollBox";
class App extends Component {
render() {
return (
<div>
<ScrollBox ref={(ref) => (this.scrollBox = ref)} />
<button onClick={() => this.scrollBox.scrollToBottom()}>
맨 밑으로
</button>
</div>
);
}
}
export default App;
‼️주의할 점
⇒ 컴포넌트가 처음 렌더링될 때는 this.scrollBox 값이 undefined이므로 this.scrollBox.scrollToBottom 값을 읽어 오는 과정에서 오류가 발생합니다.
✅ 화살표 함수 문법을 사용하여 아예 새로운 함수를 만들고 그 내부에서 this.scrollBox.scrollToBottom 메서드를 실행하면, 버튼을 누를 때(이미 한 번 렌더링을 해서 this.scrollBox를 설정한 시점) this.scrollBox.scrollToBottom 값을 읽어 와서 실행하므로 오류가 발행하지 않습니다.
'React' 카테고리의 다른 글
[React를 다루는 기술 정리] 4장 이벤트 핸들링 (0) | 2022.02.15 |
---|---|
[React를 다루는 기술 정리] 3장 컴포넌트 (0) | 2022.02.15 |
[React를 다루는 기술 정리] 2장 JSX (0) | 2022.02.08 |
댓글