Software Engineering

Components and Props in React(리액트)

JO_turn 2020. 11. 20. 23:06

확실한 정보전달을 위하여 codesandbox.io에서 실습할 예정이다.

reactjs.org/docs/components-and-props.html의 내용을 바탕으로 재정리한다.

이하 자바스크립트는 Js라고 명칭 한다.

 

Props(소품)

컴포넌트를 함수, 클래스 어떤 것으로 선언하든 자체의 props를 수정해서는 안된다.

프롭스는 변할 수 없는 데이터이다.

props의 이름을 임의로 지정해줄 수 있다.

props를 다룰때는 순수 함수처럼 동작해야 한다.

props는 부모로 컴포넌트로부터 자식 컴포넌트로 전달한다.

Component

리액트는 Component(구성요소) 단위로 개발을 한다.

하나의 의미를 가진 독립적인 단위 모듈을 사용한다.

코드가 직관적이고 재사용성이 올라간다.

컴포넌트란 하나의 커스텀 태그와도 같다고 볼 수 있다

컴포넌트는 항상 대문자로 시작해야 한다.

//소문자로 시작하는 것은 DOM태그로 취급한다.

Function Component & Class Component

컴포넌트는 함수 OR 클래스로 정의할 수 있다.

<---  함수형 컴포넌트 선언 --->

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

데이터와 함께 props를 인자로 받아들이며 React요소를 반환한다.

 

<--- 클래스형 컴포넌트 선언 --->

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

<--- 컴포넌트 만들어보기 --->

import React from "react";

function App() {
  return (
    <div>
      <Message text="Hello" name="JO turn" />
    </div>
  );
}
//최상단 컴포넌트에 Message 컴포넌트 사용하여 호출

function Message(props) {
  return (
    <div>
      <h1>{props.text}</h1>
      <h2>{props.name}</h2>
      {console.log(props)}
    </div>
  );
}
//Message 컴포넌트 생성

export default App;

export 되는 App 컴포넌트에 새로운 컴포넌트를 선언하여 사용할 수 있다.

potps를 console.log를 이용하여 찍어보면 {text : "Hello", name : "JO turn"}으로

나오는 것을 확인할 수 있다.

이것을 이용하여 구조 분해 props의 값을 "구조분해할당" 할 수 있다

//구조분해할당 : ES6 문법

import React from "react";

function App() {
  return (
    <div>
      <Message text="Hello" name="JO turn" />
    </div>
  );
}
//최상단 컴포넌트에 Message 컴포넌트 사용하여 호출

function Message({ text, name }) {
  return (
    <div>
      <h1>{text}</h1>
      <h2>{name}</h2>
    </div>
  );
}

//Message 컴포넌트 생성 인자에'구조분해할당사용'

export default App;

  구조분해 할당을 이용한 리팩토링

Extracting Components(컴포넌트 쪼개기)

<--- 쪼갤 컴포넌트의 예제 --->

import React from "react";

function App() {
  return (
    <div>
      <Comment
        date={comment.date}
        text={comment.text}
        author={comment.author}
      />
    </div>
  );
} //Comment 컴포넌트 사용

const comment = {
  date: new Date(),
  text: "I hope you enjoy learning React!",
  author: {
    name: "Hello Kitty",
    avatarUrl: "https://placekitten.com/g/64/64"
  }
};//객체선언

function formatDate(date) {
  return date.toLocaleDateString();
}//날짜나오게 하는 함수선언

function Comment(props) {
  return (
    <div>
      <div>
        <img src={props.author.avatarUrl}
             alt={props.author.name}/>
        <div>{props.author.name}</div>
      </div>
      <div>{props.text}</div>
      <div>{formatDate(props.date)}</div>
    </div>
  );
}//함수형 컴포넌트 생성

export default App;

<--- 컴포넌트를 쪼갠 후의 예제 --->

import React from "react";

function App() {
  return (
    <div>
      <Comment
        date={comment.date}
        text={comment.text}
        author={comment.author}
      />
    </div>
  );
} //Comment 컴포넌트 사용

const comment = {
  date: new Date(),
  text: "I hope you enjoy learning React!",
  author: {
    name: "Hello Kitty",
    avatarUrl: "https://placekitten.com/g/64/64"
  }
}; //객체선언

function Avatar(props) {
  return <img src={props.user.avatarUrl} 
         alt={props.user.name} />;
} //이미지 추출

function formatDate(date) {
  return date.toLocaleDateString();
} //날짜나오게 하는 함수선언

function UserInfo(props) {
  return (
    <div>
      <Avatar user={props.user} />
      <div>{props.user.name}</div>
    </div>
  );
} //이미지와 이름을 담고있는 정보 추

function Comment(props) {
  return (
    <div>
      <UserInfo user={props.author} />
      <div>{props.text}</div>
      <div>{formatDate(props.date)}</div>
    </div>
  );
}

export default App;

구성요소를 추출하는 것은 까다로운 작업처럼 보일 수 있지만 재사용이 용이하기 때문에 규모가

큰 프로젝트를 진행할 때에는 좋은 효과를 발휘할 수 있다.

주로 Button, Panel, Avatar, FeedStory, Comment를 따로 컴포넌트를 만들어 사용한다.

이전에는 클래스 컴포넌트를 주로 사용하였지만 현재는 함수 컴포넌트를 많이 사용하는 추세이다.

 

함수형 컴포넌트를 클래스형 컴포넌트로 변환하는 방법

동일한 이름의 클래스를 만든다.

//Class SameName extends React.Component

render()의 빈 메서드를 만든다.

함수의 본문을 render() 메서드의 옮긴다.

props를 this.props로 바꾼다.

Q&A

Q1. DOM을 처음 배울 때 페이지 단위로 작업하는 방법과 비교해서, 컴포넌트 단위로 개발할 때의 장점은 무엇인가요?

A. 재사용이 용이하고, 직관적이다.

Q2. 하나의 컴포넌트에서 여러 개의 엘리먼트를 리턴할 수도 있나요?

A. 빈 태그 혹은 fragment태그를 이용해 가능하다.
Q3. <Tweet> 나의 새 트윗 </Tweet>이라는 컴포넌트 사용 방법이 있다고 가정할 때, 

       컴포넌트 내에서 나의 새 트윗이라는 문자열은 어떻게 접근할 수 있나요?

A.

function Tweet(props) {
return <div>{props.children}</div>;
}

props.children를 이용해 바로 추출할 수 있다.
Q4. props를 다룰 때에 지켜야 하는 엄격한 규칙이 하나 있습니다. 무엇인가요?
A. 모든 props는 순수함수처럼 작동해야 한다.

 

출처 :reactjs.org/docs/components-and-props.html

 

Components and Props – React

A JavaScript library for building user interfaces

reactjs.org