본문 바로가기
프로그래밍/react

React 컴포넌트 클래스와 속성

by 직장인 투자자 2022. 3. 5.

React 컴포넌트 클래스

 

컴포넌트 클래스를 활용하면 기능을 느슨하게 결합된 부분으로 분리하여 코드를 재사용할 수 있다. ES6 문법을 이용하면 React.Component 클래스를 상속받아서 React 컴포넌트 클래스를 생성할 수 있다. class Child extends Parent 같은 형식으로 작성된다.

 

새로운 컴포넌트 클래스를 구현할 때는 반드시 render() 메서드를 작성해야 한다. 이 메서드는 다른 custom 컴포넌트 클래스나 html 태그로 만든 react 엘리먼트를 반환해야 한다.

 

예제

let h1 = React.createElement('h1', null, 'Hello world!')
class HelloWorld extends React.Component { // React 컴포넌트 클래스 정의
  render() {  // element 하나를 반환하는 함수인 render method 생성
    return React.createElement('div', null, h1, h1)
  }
}
ReactDOM.render(
  React.createElement(HelloWorld, null),
  document.getElementById('content')
)

실행결과

실행결과1
실행결과1

이렇게 컴포넌트로 구성하게 되면 Hello world를 여러 번 노출해야 할 때 재사용할 수 있고 이로 인해 개발 속도를 높여주고 버그를 줄일 수 있다.

 

다만 HelloWorld 엘리먼트가 모두 똑같은 것이 아쉬운데 속성을 입력해서 내용이나 동작을 변경할 수 있는 속성을 알아보자.

 

React 속성

속성을 이용해서 아래와 같이 링크 URL을 넣을 수 있다.

React.createElement('a', {href: 'http://www.naver.com'})

 

속성은 컴포넌트 내부에서는 변경할 수 없는 값으로 부모 컴포넌트는 자식의 생성 시점에 속성을 할당하게 된다. 자식 엘리먼트에서는 속성을 수정하지 않아야 한다.

 

내부적으로 React는 속성 이름을 HTML 표준 속성과 대조하여 일치하는 표준 속성이 있으면 HTML 속성으로 사용한다.

만약 일치하지 않는다면 HTML에 렌더링 하지 않고 this.props 객체에서 this.props.PROPERTY_NAME 같은 방식으로 접근할 수 있다. render method에서 활용할 수 있다.

 

예제

this.props 객체의 키는 createElement의 두 번째 매개변수로 전달한 객체의 키와 같다. this.props의 키로 id, frameworkName, title을 확인할 수 있다.

class HelloWorld extends React.Component {
  render() {
    return React.createElement(
      'h1',
      this.props, // Hello World 컴포넌트로 전달한 모든 속성을 h1 엘리먼트로 전달한다.
      'Hello ' + this.props.frameworkName + ' world!'
    )
  }
}

ReactDOM.render(
  React.createElement(
    'div',
    null,
    React.createElement(HelloWorld, {
      id: 'ember',
      frameworkName: 'Ember.js',
      title: 'A framework for creating ambitious web applications.'}),
    React.createElement(HelloWorld, {
      id: 'backbone',
      frameworkName: 'Backbone.js',
      title: 'Backbone.js gives structure to web applications...'}),
    React.createElement(HelloWorld, {
      id: 'angular',
      frameworkName: 'Angular.js',
      title: 'Superheroic JavaScript MVW Framework'})
  ),
  document.getElementById('content')
)

실행결과

실행결과2
실행결과2

반응형

'프로그래밍 > react' 카테고리의 다른 글

react란 무엇인가?  (0) 2022.02.28

댓글