✅. ref?
리엑트 프로젝트 내에서 DOM 요소에 직접 이름을 지정할 수 있습니다.
HTML id와 유사하지만 재사용되는 컴포넌트 안에서 유일해야하는 id를
중복해서 가진 DOM이 생겨 문제가 될 수 있습니다.
✅. ref 사용 상황
DOM을 꼭 직접적으로 조작해야 할 때 사용됩니다.
특정 input에 포커스 주기
스크롤 박스 조작하기
Canvas 요소에 그림 그리기
✅3. ref 사용 방법
콜백 함수, createRef 두 가지 방법이 있습니다.
✅ 3.1. 콜백 함수를 통한 ref 설정
ref를 달고자 하는 요소에 ref라는 콜백 함수를 props로 전달합니다.
<input ref={(ref) => this.input=ref}/>
this.input은 input 요소의 DOM을 가리킨다.
this.input의 input name은 자유롭게 지정 가능하다.(this.user)
✅ 3.2 createRef
리엑트에 내장되어 있는 함수로 리엑트 v16.3 부터 도입 됐습니다.
import {Component} from 'react'
class RefSample extends Component {
input = React.createRef();
handleFocus = () => {
this.input.current.focus();
}
render() {
return (
<div>
<input ref={this.input}/>
</div>
);
}
}
export default RefSample;
컴포넌트 내부에서 멤버 변수로 ‘React.createRef()’를 담아 준다.
해당 멤버 변수를 ref를 달고자하는 요소에 ‘ref props’로 넣어 준다.
DOM요소에 접근하려면 ‘this.input.current’를 조회 한다.
✅ 4. 컴포넌트에 ref 지정하기
컴포넌트 내부의 DOM을 컴포넌트 외부에서 사용할 때 사용하는 방법입니다.
✅ 4.1. 사용법
<input ref={(ref) => {this.myComponent=ref}}/>
✅ 4.2. 컴포넌트에 적용해보기
ScrollBox 컴포넌트 최상위 DOM에 ref 지정하기
ScrollBox 컴포넌트에 메서드 생성
import {Component} from 'react'
class ScrollBox extends Component {
render() {
const style = {};
const innerStyle = {};
}
scrollToBottom = () => {
const {scrollHight, clienHeight} = this.box;
this.box.scrollTop = scrollHeight - cleanHeight
}
return (
<div
style={style}
ref={(ref) => {this.box=ref}}>
<div style={}innerStyle/>
</div>
);
}
export default ScrollBox;
App.js에 불러온 컴포넌트에 ref 지정 후 메서드 사용하기
import { Component } from 'react'
import ScrollBox from './ScrollBox'
class App extends Component {
render() {
return (
<div>
<ScrollBox ref = {(ref) => this.scrollBox=ref}>
<button onClick = {() => this.scrollBox.scrollToBottom()}>
맨 밑으로
</button>
</div>
);
}
}
export default App;
div => scrollToBottom() => ScrollBox => button onClick
5. 주의할 점
리엑트는 부모에서 자식으로 흐름을 만들게끔 설계되어있기 때문에
규모가 커졌을 때 ref를 남용할 경우 스파게티 코드가되어 유지 보수가 불가능해 집니다.
ref를 사용하지 않고도 원하는 기능을 구현할 수 있는지 반드시 고려하세요.
[출처] https://w00sik.github.io/posts/study01/
'React' 카테고리의 다른 글
[axios&api] http://localhost:3000/ & http://localhost:4000/ (0) | 2024.01.06 |
---|---|
이벤트 핸들링(Event Handling) (1) | 2024.01.05 |
컴포넌트 분리's 정석 (0) | 2024.01.05 |
React : Button Modal Input Select 기본기능 구현 (1) | 2024.01.05 |
컴포넌트 (Component) (1) | 2024.01.04 |