34_React p.1

charlie_·2021년 7월 19일
1

TIL

목록 보기
33/42
post-thumbnail

React의 등장배경

  • 요약
    :: 웹 애플리케이션의 등장
    :: 페이스북에서 "지속적으로 데이터가 변화하는 대규모 애플리케이션 구축하는 것"을 목표로 개발한 라이브러리가 React

웹사이트가 단방향 정보제공의 기능을 한다면, 웹 애플리케이션은 유저와 양방향 소통 혹은 상호작용하는 기능을 한다. (ex. 페이스북의 댓글, 좋아요, 싫어요 등) 그래서 요즘은 보여지는 것(UI: User Interface)뿐만 아니라 할 수 있는 것(UX: User Experience)도 많다.

이로 인해, 데이터의 규모가 커지고 복잡해지며 생산성과 효율성을 높이는
새로운 프레임워크와 라이브러리들이 등장한다. 그 중에 페이스북에서
"지속적으로 데이터가 변화하는 대규모 애플리케이션 구축하는 것"을 목표로 개발한 라이브러리가 React이다.

설치방법

1) node.js를 설치한다.
2) 터미널을 열고 React 개발 환경을 설치할 폴더에 위치한다.
3) React 사용에 필요한 개발환경을 설치한다.

ex. 바탕화면(desktop)에 폴더를 만든 경우

1. 폴더 진입
cd Desktop/폴더명

2. test-react 프로젝트 설치 (개발환경 설치)
npx create-react-app test-react

3. test-react 프로젝트 진입
cd test-react

4. 로컬 서버 띄우기
npm start

React의 주요 개념

1) JSX (Javascript Syntax eXtension)

:: 자바스크립트의 문법에 HTML을 혼합하여 사용하는 문법으로 JSX문법을 브라우저가 읽기 위해서는 바벨(Babel)이 필요하다.

ex.
const test = <h1>Hello</h1>
  • JSX를 사용할 때는 지켜야하는 몇 가지 규칙이 있다. 아래에서 알아보자.

2) Component

:: 재활용 가능한 UI 구성 단위

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

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

// const test = <Welcome name="Sara" />; // element
// <Welcome name="Sara" /> // component
// name="Sara" // Welcome 컴포넌트의 props
  • 리액트는 소문자로 시작하면 태그, 대문자로 시작하면 Component로 인식한다.
    예를 들어, <div />는 HTML div 태그를 나타내지만, <Welcome />은 컴포넌트를 나타낸다.

2-1) Component 추출

아래의 코드에서 Avatar를 Component로 추출해보자.

function Comment(props) {
  return (
    <div className="Comment">
      <div className="UserInfo">
        <img className="Avatar"
          src={props.author.avatarUrl}
          alt={props.author.name}
        />
        <div className="UserInfo-name">
          {props.author.name}
        </div>
      </div>
    </div>
  );
}

Comment 컴포넌트는 author와 name을 필요로 한다고 해서 Avatar 컴포넌트도 반드시 author를 props로 사용할 필요는 없다. 그러니 알아보기 쉽게 user로 변경하자.

function Avatar(props) {
  return (
    <img className="Avatar"
      src={props.user.avatarUrl}
      alt={props.user.name}
    />
  );
}

분리한 Avatar 컴포넌트를 Comment 컴포넌트에서 호출한 모습이다.

function Comment(props) {
  return (
    <div className="Comment">
      <div className="UserInfo">
        <Avatar user={props.author} />
        <div className="UserInfo-name">
          {props.author.name}
        </div>
      </div>
    </div>
  );
}

3) Props

:: 부모 컴포넌트로부터 전달 받은, 데이터를 지니고 있는 객체.
→ 위의 코드를 보면 Comment(부모) 컴포넌트에서 {props.author}라는 데이터를,
user객체에 담아 Avatar(자식) 컴포넌트에 전달하면서 호출하고 있다.

:: Avatar 컴포넌트의 props는 user={props.author}.
(+ user는 props의 key이고, {props.author}는 user의 value이다.)

:: 이번에는 class형 컴포넌트로 알아보자.

  • 부모 컴포넌트
import React from 'react';
import Child from './Child';

class Parent extends React.Component {
  constructor() {
    super();
    this.state = {
      color: 'red'
    };
  }

  render() {
    return (
      <div>
        <h1>Parent Component</h1>
        <Child titleColor={this.state.color}/>
      </div>
    );
  }
}

export default Parent;

:: Child의 props는 titleColor={this.state.color}고,
데이터인 {this.state.color}의 값은 red다.
부모 컴포넌트의 constructor에서 상태(state color: red)의 값을 지정하고,
데이터의 형식(={this.state.color})으로 Child props의 value를 전달
했다.
이 때 titleColor는 Child props의 key이다.

:: 정리하면 Child props = {titleColor: "red"}라는 말이다.

  • 자식 컴포넌트
import React from 'react';

class Child extends React.Component {
  render() {
    //console.log(this.props);
   
    return (
      <div>
        <h1 style={{color : this.props.titleColor}}>
        Child Component
        </h1>
      </div>
    );
  }
}

export default Child;

앞의 내용을 console.log로 확인해보면 아래의 결과가 나오는 것을 볼 수 있다.

console.log(this) // Child
console.log(this.props) // {titleColor: "red"}
console.log(this.props.titleColor) // red

3) State

:: 화면에 보여줄 컴포넌트의 UI 정보(상태)를 지니고 있는 객체

:: state에 값을 지정해서, 데이터의 형식{this.state.color}으로 props의 value에 전달하면 끝.

:: 읽는 방법은 Props와 크게 다르지 않다.

console.log(this) // 해당 컴포넌트
console.log(this.state) // 해당 state 객체
console.log(this.state.color) // state 객체의 특정 key 값
profile
매일 하루에 딱 한 걸음만

0개의 댓글

Powered by GraphCDN, the GraphQL CDN