SW프로그래밍/React
[React] Ref
고랑이.
2021. 3. 11. 17:45
Ref란?
- render 메서드에서 생성된 DOM 노드나 React 엘리먼트에 접근하는 방법을 제공.
- id와 같은 역할을 하지만, ref에서는 컴포넌트 내부에서만 작동하기 때문에 id중복 문제를 해결할 수 있음.
//jquery
$("#input").val("abc");
$("#input").focus();
const getValue = $("#input").val();
<input tyle="text" id="input"/>
//react
const inputRef = useRef();
inputRef.current.value = "abc";
inputRef.current.focus();
const getValue = inputRef.current.value;
<input type="text" ref={inputRef}/>
ref를 사용해야 하는 경우.
- 특정 input에 포커스 주기
- 스크롤박스 조작하기
- canvas 요소에 그림그리기 등
ref 설정
1. 콜백 함수로 설정
import React, { Component } from 'react';
class refSample extends Component {
render() {
return (
<div>
<input ref={(ref) => {this.inputRef=ref}} />
</div>
);
}
}
export default refSample;
ref를 달고자 하는 요소에 ref라는 콜백 함수를 props로 전달.
파라미터로 받은 ref를 컴포넌트의 멤버 변수로 설정
-> this.inputRef 는 input요소의 Dom을 가리킨다.
2. createRef로 설정
import React, { Component } from 'react';
class refSample extends Component {
inputRef = React.createRef();
render() {
return (
<div>
<input ref={this.inputRef}/>
</div>
);
}
}
export default refSample;
컴포넌트 내부에서 React.createRef()로 멤버변수를 선언.
변수를 요소의 ref props로 넣어줌.
컴포넌트에 ref 달기
<MyComponent ref={(ref) => {this.componentRef=ref}}/>
import React, { Component } from 'react';
class MyComponent extends Component {
input = React.createRef();
handleClick = (e) => {
//handle event
}
render() {
return (
<div>
<input ref={this.input} onChange={this.handleClick}/>
</div>
);
}
}
export default MyComponent;
컴포넌트에 설정한 ref로 MyComponent 컴포넌트 내부의 메서드나 멤버 변수에 접근 가능.
componentRef.handleClick, componentRef.input 등
예시)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
import React, { Component } from 'react';
class ScrollBox extends Component {
scrollToBottom = () => {
const {scrollHeight, clientHeight} = this.boxRef;
this.boxRef.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.boxRef = ref}}>
<div style={innerStyle}/>
</div>
);
}
}
export default ScrollBox;
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
import React, { Component } from 'react';
import ScrollBox from './scrollBox_ref';
class App extends Component {
render() {
return (
<div>
<ScrollBox ref={(ref) => this.scrollBox = ref}/>
<button onClick={() => this.scrollBox.scrollToBottom()}>맨 밑으로</button>
</div>
);
}
}
export default App;
|
ScrollBox 컴포넌트에 scrollbox ref 생성,
부모 컴포넌트(App.js)에서 컴포넌트 내부의 scrollToBottom() 메서드를 호출
참조 : 리액트를 다루는 기술(김민준 / 길벗)