본문 바로가기
Javascript/react

React 주요 개념 Components and props

by Redking

컴포넌트는 하나의 조각이라고 생각하시면 됩니다. 그리고 각각의 컴포넌트는 개별적으로 컨트롤이 가능합니다.

개념적으로 컴포넌트는 javascript 함수와 유사하고 "props"라는 임의의 값을 입력받은 후 화면에 react 엘리먼트를 반환합니다.

 

컴포넌트는 함수 컴포넌트와 클래스 컴포넌트가 있습니다. 이 페이지에서는 두 가지 모두 다뤄보겠습니다.

function Welcome(props) {  // 함수 컴포넌트
    return <h1>hello, {props,name}</h1>;
}

class Welcome extends React.Component {  // 클래스 컴포넌트
    render() {
        return <h1>Hello, {this.props.name}</h1>;
    }
}

react의 관점에서 볼 때 두가지 유형의 컴포넌트는 동일하지만 몇 가지 차이점이 있습니다.

 

우선 함수 컴포넌트의 특징은 객체 인자를 받아올 수 있다는 점입니다. 받아온 인자를 바탕으로 react 엘리먼트를 반환하고 이러한 컴포넌트는 javascript 함수이기 때문에 함수 컴포넌트라고 합니다.

 

클래스 컴포넌트는 ComponentWilllMount(), ComponentDidMount()등과 같은 클래스 컴포넌트에서만 사용 가능한 메서드를 사용할 수 있다. 

예전에는 이러한 동작들이 클래스 컴포넌트에서만 사용 가능하였지만 React 16.8에 추가된 "Hook"으로 인해 함수형 컴포넌트에서도 사용 가능해졌습다.

 

React는 사용자 정의 컴포넌트로 작성한 엘리먼트를 발견하면 JSX 어트리뷰트와 자식을 해당 컴포넌트에 단일 객체로 전달합니다. 이 객체를 props라고 합니다.

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

const element = <Welcome name="Sara" />;
ReactDOM.render(
  element,
  document.getElementById('root')
);

구조 파악

  1. <Welcome name="Sara"/>를 element 변수로 생성하여 이를 ReactDOM.render()로 호출합니다.
  2. React는 {name: 'Sara'}를 props로 하여 Welcome 컴포넌트를 호출합니다.
  3. Welcome 컴포넌트는 <h1> Hello, Sara </h1>를 반환합니다.
  4. ReactDOM은 이를 바탕으로 DOM을 업데이트합니다.

컴포넌트 합성과 추출

컴포넌트는 자신의 출력에 다른 컴포넌트를 참조할 수 있습니다. 이 개념을 잘 이용한다면 컴포넌트를 작게 쪼개어 사용할 수 있습니다.

function Profile(props) {
    return (
    	<div className="UserProfile">
            <img className="UserProfile-image" src="{props.profile.image}"/>
            <p class="UserProfile-name">이름: {props.profile.name}</p>
            <p class="UserProfile-gender">성별: {props.profile.gender}</p>
        </div> 
    );
};

위에 생성한 Profile 컴포넌트는 유저의 프로필에 대한 컴포넌트로 프로필 사진, 이름, 성별, 전화번호 각각의 구성요소들이 모두 중첩 구조로 이루어져 있어 변경하기 어려울 수 있습니다. 또한 각 구성요소를 개별적으로 재사용하기도 어렵기 때문에 작게 쪼개어 보겠습니다.

 


function ProfileImage(props) {
    return (
        <img className="UserProfile-image" src={props.profile.image} />
    );
};

function ProfileInfo(props) {
    return (
        <div className="UserProfileInfo">
            <ProfileImage profile={props.profile} />
            <p class="UserProfile-name">이름: {props.profile.name}</p>
            <p class="UserProfile-gender">성별: {props.profile.gender}</p>
        </div>
    );
};

function Profile(props) {
    return (
        <div className="UserProfile">
            <ProfileInfo profile={props.user} />
        </div>
    );
};

const profile = {

    webUser: {
        name: '유저',
        image: 'https://dummyimage.com/600x400/000/fff',
        gender: '남'
    }
};
ReactDOM.render(
    <Profile
        user={profile.webUser}
    />,
    document.getElementById('root')
);

하나의 컴포넌트로 해결할 수 있는 코드를 여러 개의 컴포넌트로 파편화하는 점에 대해 다소 피곤할 수 있으나 이후 재사용 가능한 컴포넌트를 만들어 놓는 것은 프로젝트 사이즈가 커질수록 두각을 나타냅니다.

'Javascript > react' 카테고리의 다른 글

React 주요 개념 Event 처리  (0) 2021.03.30
React 주요 개념 Lifecycle of Component  (0) 2021.03.29
React 주요 개념 State  (0) 2021.03.29
React 주요 개념 엘리먼트 렌더링  (0) 2021.03.25
React 주요 개념 JSX  (0) 2021.03.24

댓글