happyso
study with happyso
happyso
전체 방문자
오늘
어제
  • 분류 전체보기 (302)
    • GIT (3)
    • 컴퓨터 기본 개념 (29)
    • 알고리즘 (125)
      • 알고리즘 문제 (115)
      • 알고리즘 개념 (10)
    • Go (2)
    • 클라우드 (54)
      • DevOps (4)
      • Kubernetes(쿠버네티스) (33)
      • AWS (6)
      • CKA (8)
    • 리눅스(Linux) (18)
      • 컨테이너(Container) (8)
    • Front (22)
      • JavaScript (2)
      • React (20)
    • Python (21)
      • Python 웹 크롤링 (11)
      • Django (7)
      • MachineLearning (3)
    • 데이터베이스 (6)
      • MariaDB (2)
      • MongoDB (4)
    • C언어 (5)
    • Trouble Shooting (2)
    • 네트워크 (8)
      • CCNA (5)
    • 보안 (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 15
  • Patch
  • edit
  • 18
  • apply
  • kubernetes
  • replace

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
happyso

study with happyso

[React] 기본개념
Front/React

[React] 기본개념

2020. 11. 4. 01:55

리액트를 다루는 기술

https://velopert.com/3613

 

create-react-app 설치

C:\> mkdir react

C:\> cd react

C:\react> npm install -g create-react-app

 

hello-react 프로젝트 생성

C:\react> create-react-app hello-react

 

hello-react 프로젝트를 실행

C:\react> cd hello-react

C:\react\hello-react> npm start

 

> hello-react@0.1.0 start C:\react\hello-react

> react-scripts start







https://velopert.com/3626

 

JSX 에서 유의할 사항

태그는 반드시 닫아야 한다.

<img … /> 

<div> … </div>

 

하나의 루트 엘리먼트가 존재해야 한다. 

<div>
      <div className="App">
		:
      </div>
      <div>
		:
      </div>
</div>

 

→ 2개의 <div>를 묶어주는 역할의 <div>를 사용하면 불필요한 DOM 객체를 사용하게 됨

 

 

<>
      <div className="App">
		:
      </div>
      <div>
		:
      </div>
</>

 

<Fragment>
      <div className="App">
		:
      </div>
      <div>
		:
      </div>
</Fragment>

 

 

 

컴포넌트를 선언하는 방법1. 함수 형태

import logo from './logo.svg';
import './App.css';
 
function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}
 
export default App;

 

 

컴포넌트를 선언하는 방법2. 클래스 형태

→ 반드시 render() 함수를 정의해야 함

import logo from './logo.svg';
import React from 'react';
import './App.css';
 
class App extends React.Component {
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <p>
            Edit <code>src/App.js</code> and save to reload.
          </p>
          <a
            className="App-link"
            href="https://reactjs.org"
            target="_blank"
            rel="noopener noreferrer"
          >
            Learn React
          </a>
        </header>
      </div>
    );
  }
}
 
export default App;

 

JSX 내부에서 JavaScript 사용

import React from 'react';
import './App.css';
 
class App extends React.Component {
  render() {
    const style = {
      backgroundColor: 'black',   // background-color
      color: 'white', 
      fontSize: '12px'
    };
    const value = 1;
    const name = "React";
    return (
      <>
        { /* 주석1 */ }
        { // 주석2
          }
        <div /* 주석3 */
             // 주석4
        ></div>
        <div style={style}>Hello {name}!!!</div>
        <div className="App">{ name == 'React' ? "Hello React" : "안녕 리액트" }</div>
        <div>
          /* 주석이 아닙니다. */
          // 이것도 주석이 아닙니다. 
          {
              (function() {
                if (value == 1) return "하나";
                if (value == 2) return "둘";
              })()
          }
        </div>
      </>
    );
  }
}
 
export default App;

 

컴포넌트 생성

c:\react\hello-react\src\MyName.js 파일을 생성 ⇒ 전달된 이름을 출력

import React, { Component } from 'react';
 
class MyName extends Component {
    //  상태(state) 변수
    //  해당 컴포넌트 내에서 유지 관리하는 값
    state = {
        number: 0
    };
 
    //  생성자 함수 ==> 초기화 
    constructor(props) {
        super(props);
        this.state = {
            number: 0
        };
    }
 
    onIncrease = () => {
        //  상태 변수를 변경할 때는 반드시 setState() 메소드를 이용
        this.setState({ number: this.state.number + 1});
    }
 
    onDecrease = () => {
        this.setState({ number: this.state.number - 1});
    }
 
    render() {
        return (
            <>
                { /* props: 부모로 부터 전달되는 값 */ }
                안녕하세요. 나는 {this.props.name} 입니다. 
 
                <h1>몇 번 클릭했는지 궁금...</h1>
                <div>{ this.state.number }</div>
                <button onClick={this.onIncrease}> + </button>
                <button onClick={this.onDecrease}> - </button>
                
            </>
        );
    }
}
 
export default MyName;

 

c:\react\hello-react\src\App.js ⇒ MyName.js에서 정의한 컴포넌트를 가져와서 사용

import React from 'react';
import './App.css';
import MyName from './MyName';
import MyName2 from './MyName2';
 
class App extends React.Component {
  render() {
    return (
      <>
        <MyName name="홍길동"></MyName>
        <br/>
        <MyName name="리액트"/>
        <br/>
        <MyName2 name="또길동" age="23"/>
      </>
    );
  }
}
 
export default App;

 

c:\react\hello-react\src\MyName2.js 파일을 생성 ⇒ 함수형 컴포넌트

import React from 'react';
import MyName from './MyName';
 
function MyName2({ name, age }) {
    return (
        <>
            안녕하세요. 나는 { name }이고, 나이는 { age } 입니다.
        </>
    );
}
 
export default MyName2;

 

DOM 스크립트와 리액트 비교

C:\react> mkdir hello-react2

C:\react> cd hello-react2

C:\react\hello-react2\todo.html 파일을 생성

<html>
    <body>
        <div class="todo">
            <h3>할 일 목록</h3>
            <ul class="list"></ul>
            <input class="desc" type="text" />
            <button onclick="onAdd()">추가</button>
            <button onclick="onSaveToServer()">서버에 저장</button>
        </div>
        <script>
            let currentId = 1;
            const todoList = [];
            function onAdd() {
                const inputEl = document.querySelector('.todo .desc');
                const todo = { id: currentId, desc: inputEl.value };
                todoList.push(todo);
                currentId ++;
                const elemList = document.querySelector('.todo .list');
                const liEl = makeTodoElement(todo);
                elemList.appendChild(liEl);
            }
            function makeTodoElement(todo) {
                const liEl = document.createElement('li');
                const spanEl = document.createElement('span');
                const buttonEl = document.createElement('button');
                spanEl.innerHTML = todo.desc;
                buttonEl.innerHTML = '삭제';
                buttonEl.dataset.id = todo.id;
                buttonEl.onclick = onDelete;
                liEl.appendChild(spanEl);
                liEl.appendChild(buttonEl);
                return liEl;
            }
            function onDelete(e) {
                const id = Number(e.target.dataset.id);
                const index = todoList.findIndex(item => item.id === id);
                if (index >= 0) {
                    todoList.splice(index, 1);
                    const elemList = document.querySelector('.todo .list');
                    const liEl = e.target.parentNode;
                    elemList.removeChild(liEl);
                }
            }
            function onSaveToServer() {
                //  todoList 전송
            }
        </script>
    </body>
</html>

 

'Front > React' 카테고리의 다른 글

[React] 외부 API를 연동하여 뉴스 뷰어 만들기  (0) 2021.01.12
[React] 리액트 라우터 부가 기능  (0) 2021.01.09
[React] 서브 라우트  (0) 2021.01.09
[React] URL 파라미터와 쿼리  (0) 2021.01.09
React 배우기  (0) 2021.01.05
    'Front/React' 카테고리의 다른 글
    • [React] 리액트 라우터 부가 기능
    • [React] 서브 라우트
    • [React] URL 파라미터와 쿼리
    • React 배우기
    happyso
    happyso

    티스토리툴바