티스토리 뷰

IT/React

리액트 컴포넌트 ref 속성값 사용

탐구소년 2020. 9. 24. 12:36

 

리액트 어플리케이션을 작업하다 보면 가상 DOM요소에 직접 접근해야 하는 상황이 있을 수 있습니다. 이와 같은 상황에서 순수 자바스크립트의 경우에는 다음과 같은 접근을 사용합니다. 

1
document.getElementById('ID')

 

위와 같이 요소에 대한 직접 접근을 하고자 할 때, 리액트 컴포넌트에서는 ref 속성값을 이용하면 됩니다. ref 속성값을 이용하면 자식 요소에 직접 접근이 가능합니다. 

 

다음은 ref를 이용한 간단한 예입니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import React from 'react';
import './App.css';
 
class App extends React.Component{
  textRef = React.createRef();
  componentDidMount(){
    this.checkRef()
  }
  checkRef(){
    console.log(this.textRef.current)
    this.textRef.current.focus();
  }
  render(){
    return <div>
      <input type="text" ref={this.textRef} />
    </div>
  }
}
 
export default App;

5번 줄에서 createRef 함수가 반환하는 ref 개체를 이용해서 특정 DOM 객체에 접근할 수 있도록 했습니다. 이제 접근하고자 하는 객체의 ref 속성 값에 textRef를 입력하게 되면, App 컴포넌트의 textRef 속성값은 input 객체를 가리키게 되는 것입니다. 결과적으로 이 컴포넌트는 렌더링이 완료되면 인풋 요소로 포커스가 이동하는 동작을 수행할 것입니다. 

 

다음은 자식 컴포넌트에 ref 속성 값을 사용하고, 그것을 활용하는 예제입니다. 

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
import React from 'react';
import './App.css';
 
class InputArea extends React.Component{
  render(){
    return <input type="text" ref={this.props.textRef} />
  }
}
 
class App extends React.Component{
  constructor(props){
    super(props)
    this.textRef = React.createRef();
  }
  componentDidMount(){
    this.checkRef()
  }
  checkRef(){
    console.log(this.textRef.current)
    this.textRef.current.focus();
  }
  render(){
    return <div>
      <InputArea textRef={this.textRef}/>
    </div>
  }
}
 
export default App;

자식 컴포넌트의 textRef 속성에는 부모의 textRef가 전달되었습니다. 이렇게 되면 부모의 textRef가 가리키는 것이 자식 컴포넌트의 가상 요소가 될 수 있습니다. 이 경우 결과는 첫 번째 예제와 동일합니다.

 

추가로 위 예제에서 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
33
class InputArea extends React.Component{
  render(){
    return <input 
    onChange={this.props.handleInputTextChange}
    type="text" ref={this.props.textRef} />
  }
}
 
class App extends React.Component{
 
  constructor(props){
    super(props)
    this.state = {
      text : ""
    }
  }
 
 
  // 변경된 값을 state에 적용하는 함수 추가
  handleInputTextChange = (e) => {
    this.setState({
      text: e.target.value
    })
  }
 
  render(){
    return <div>
      <InputArea handleInputTextChange={this.handleInputTextChange}
      textRef={this.textRef}/>
      <p>{this.state.text}</p>
    </div>
  }
}

끝으로 결과를 보이면서 마무리하도록 하겠습니다.

 

 

 

댓글
공지사항