티스토리 뷰

 

React.Component

 

최신 자바스크립트에서는 객체를 만들기 위한 설계도의 개념인 class가 추가되었습니다. 그리고 리액트를 사용해 컴포넌트를 새로 만들 때는 React.Component라는 클래스를 기반으로 생성하는 것이 가능합니다. 

 

아래는 class 기반의 컴포넌트를 적용한 예제입니다. 이 글 이전의 글에서 사용했던 예제와 거의 흡사합니다.

 

프로젝트 구조

 

index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script crossorigin 
  src="https://unpkg.com/react@16/umd/react.development.js">
  </script>
  <script crossorigin 
  src="https://unpkg.com/react-dom@16/umd/react-dom.development.js">
  </script>
  <title>React Simple Example</title>
</head>
<body>
  <!-- 타겟 컨테이너 -->
  <div id="react-container"></div>
  <!-- <script src="sample.js"></script> -->
  <script src="sample-class-component.js"></script>
</body>
</html>

 

sample-class-component.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class nameList extends React.Component {
 
  renderListItem(name, i) {
    return React.createElement("li", { key: i }, name)
  }
 
  render() {
    return React.createElement("ul", {className: "names"},
      this.props.items.map(this.renderListItem)
    )
  }
 
}
 
const items = ["박지성""이영표""이운재"]
 
ReactDOM.render(
  React.createElement(nameList, {items}, null),
  document.getElementById('react-container')
)

위의 코드에서는 nameList라는 이름의 클래스를 정의하고 있습니다. 이 클래스는 React.Components를 확장(extends)하여 만든 클래스로, 리액트의 컴포넌트를 정의할 수 있는 클래스입니다. 즉 nameList는 가상 DOM을 생성하기 위해 정의한 설계도의 개념입니다.

18번 줄의 React.createElement를 보시면 인자로 nameList와 items를 전달하고 있는 것이 보이는데, 이는 nameList라는 요소에 items라는 속성을 전달한 것입니다. 이렇게 전달된 속성은 클래스 내에서 props라는 객체에 보관이 됩니다. 따라서 클래스 내에서(9번 줄) items라는 속성값에 접근하는 것이 가능해집니다. 9번 줄에서 사용하고 있는 함수 renderListItem은, 배열에 들어있는 데이터 하나하나를 li 요소로 만들어 반환하는 역할을 하는 함수입니다.

 

아래는 위 코드의 결과(웹 문서)입니다. 

 

 

댓글
공지사항