반응형
React ref
- DOM을직접 제어해야 할 경우 ref를 활용하여 이름을 부여하여 컴포넌트 내부에서만 활용하도록 하는 기능
- state로 제어 불가능한 경우 ref를 활용해야 하는 경우
- 특정 input에 focus
- 스크롤 박스 제어
- Canvas 요소 사용
- 다른 컴포넌트 간에 데이터 교류에 ref 사용 x
ref 사용방법
1. callback 함수 활용
- 기본적으로 사용되는 방식
- ref 콜백함수를 props로 전달하며, 콜백함수는 ref값을 파라미터로 전달받고, 함수내부에서 파라미터로 받은 ref를 컴포넌트의 멤버 변수로 설정
// this.input이 input 요소의 DOM을 가리킴
<input ref={(ref)=>{this.input=ref}}/>
2. createRef 활용
- 리액트 v16.3이상 지원
- 내장함수 createRef 사용 시 간결한 코드 사용 가능
- 사용방법
- 컴포넌트 내부에서 멤버 변수로 React.createRef()를 담아 줌
- 해당 멤버 변수를 ref를 달고자 하는 요소에 ref.props로 설정
- 설정한 DOM 접근방법 : this.변수.current
import React, { Component } from 'react';
class ExRef extends Component {
input = React.createRef();
mFocus = () => {
this.input.current.focus();
};
render() {
return (
<>
<input ref={this.input} />
<button onClick={this.mFocus}>Click</button>
</>
);
}
}
export default ExRef;
컴포넌트 ref
- 컴포넌트 내부에 있는 DOM을 컴포넌트 외부에서 사용할 때 활용
- 사용순서
- 컴포넌트 생성
- 컴포넌트에 ref
- ref를 활용하여 컴포넌트 내부 메서드 및 변수 호출
// [App.js]
import React, { Component } from 'react';
import ExRef from './ExRef';
class App extends Component {
render() {
return (
<>
{/* ExRef 내부의 메서드 및 멤버변수에 접근 강능 */}
<ExRef ref={(ref) => (this.Exref = ref)} />
<button onClick={() => this.Exref.scrollToBtm()}>goto Btm</button>
</>
);
}
}
export default App;
// [ExRef.js]
import React, { Component } from 'react';
class ExRef extends Component {
scrollToBtm = () => {
const { scrollHeight, clientHeight } = this.box;
this.box.scrollTop = scrollHeight - clientHeight;
};
render() {
const style = {
border: '1px solid black',
height: 100,
width: 100,
overflow: 'auto',
position: 'relative',
};
const innerStyle = {
width: '100%',
height: '500px',
background: 'red',
};
return (
<div
style={style}
ref={(ref) => {
this.box = ref;
}}
>
<div style={innerStyle} />
</div>
);
}
}
export default ExRef;
반응형
'React' 카테고리의 다른 글
[React] React LifeCycle (0) | 2023.12.28 |
---|---|
[React] React Event (0) | 2023.12.21 |
[React] React state (0) | 2023.12.18 |
[React] 기본 코드 설명 (0) | 2023.12.15 |
[React] React 기본 코드 (0) | 2023.11.08 |