개발세발

React - 2️⃣ (한입 크기로 잘라먹는 리액트) 본문

코딩공부/React

React - 2️⃣ (한입 크기로 잘라먹는 리액트)

뉼👩🏻‍💻 2022. 11. 24. 22:17
728x90
반응형
SMALL

 

왜 리액트인가 

 

1. 

산탄총 수술 (Shotgun Surgey) 

:중복 코드로 인해, 중복코드의 변경을 반영하기 위해 동시에 모든 것을 하나씩 수정을 하는 것 

이러한 상황을 효과적으로 해결할 수 있게 해줌 

- 컴포넌트로 하나씩 대입하기 때문에 컴포넌트를 변경하면 모든 사항이 일괄적으로 변경된다 

 

React 는 Component 기반의 UI 라이브러리 

 

2. 선언형 프로그래밍이 가능 

1) 명령형 프로그래밍 

: 절차를 하나하나씩 다 나열해야 함 (결과를 하나씩 가져와서 저장한다, 만약에 a경우라면 더하기를, b경우라면 빼기를 해준다)

- jQuery 

 

2) 선언형 프로그램

: 목적을 명시하면 바로 결과가 나옴  (1을 누르면 값을 더하고 결과에 저장한다) 

- React 

 

 

3. Virtual DOM 

변경되는 사항을 변경되는 사항만 다시 렌더링이 가능하다 

 

 

 

* Webpack 

: 다수의 자바스크립트 파일을 하나의 파일로 합쳐주는 모듈 번들 라이브러리 

 

* Babel

: JSX 등의 쉽고 직관적인 자바스크립트 문법을 사용할 수 있도록 해주는 라이브러리 

 

Boiler Plate

 : 빵 틀의 역할을 하는 패키지를 의미 

 

Creat React App = Boiler Plate

: 리액트를 만드는 데 필요한 기본적인 패키지를 모아둔 패키지

- create react app 도 nodejs기반의 패키지 이므로 node 모듈이 같이 설치됨 

 

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <!--
      manifest.json provides metadata used when your web app is installed on a
      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
    -->
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <!--
      Notice the use of %PUBLIC_URL% in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
  </body>
</html>

 

 

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

 

 

 

**

npm i  = npm install 

 

- 지금 사용하진 않고 모바일 환경에서 사용할 때 사용되는 것들

 

robots.txt 

: 구글이나 네이버 등에서 웹사이트를 수집해 할때 disllow 등을 설정할 수 있는 것 

 

- src 폴더

src : source 

 

 

JSX (Javascript Extension)

: js와 html을 합쳐서 사용하는 문법

 

es module 시스템

export default 로 1개의 값만 내보낼 수 있음 

 

index.js 에서 app.js에서 export한 값을 사용할 때 
받아오는 변수의 이름은 바꿔써도 정상적으로 실행이 된다 
대신 <React.StricMode>안의 값도 바꿔줘야 한다 

- 하지만 사회적 합의가 있기에... 바꾸지 않는다 

 

 

 

JSX 문법 사용시 반드시 하나의 부모 태그가 필요하다 

<div></div>

<React.Fragement></React.Fragement>

<></>

또는 <React.Fragement>를 통해 최상위 태그를 대신 사용할 수 있다 

 

 

스타일 태그 적용 

 

1. 인라인 태그에 작성

2. style 객체 생성 후 사용 

 

 

JSX의 중괄호 안에는 값을 포함할 수 있지만 숫자나 문자만 올 수 있다 

➡️ 배열, 불리언 등은 올 수 없음 

하지만 삼항연사자를 활용할 수 있고 그렇게 사용하면 true, false값을 반환할 수 있다 

 

 

* state(상태)

: 계속해서 변화하는 특정 상태

상태에 따라 각각 다른 동작을 함 

 

const [author, setAutor] = useState(""); // 기본 값 ""
   
const [count, setCount] = useState(10); //기본 값 o

 

 

-+ 버튼으로 숫자 변경하기 

 

OddEvenResult.jsx

import React, { useState } from "react";
import OddEvenResult from "./OddEvenResult";

const Counter = ({ initialValue }) => {
  console.log({ initialValue });
  const [count, setCount] = useState(10);

  const onIncrease = () => {
    setCount(count + 1);
  };

  // 선언식으로 작성해도 됨
  // function onIncrease() {
  //   setCount(count + 1);
  // }

  const onDecrease = () => {
    setCount(count - 1);
  };
  return (
    <div>
      <h2>{count}</h2>
      <button onClick={onIncrease}>+</button>
      <button onClick={onDecrease}>-</button>
      <OddEvenResult count={count} />
    </div>
  );
};

export default Counter;

 

Container.jsx

import React, { Children } from "react";

const Container = ({ children }) => {
  return (
    <div style={{ margin: 20, padding: 20, border: "1px solid black" }}>
      {children}
    </div>
  );
};

export default Container;

 

Counter.jsx

import React, { useState } from "react";
import OddEvenResult from "./OddEvenResult";

const Counter = ({ initialValue }) => {
  console.log({ initialValue });
  const [count, setCount] = useState(10);

  const onIncrease = () => {
    setCount(count + 1);
  };

  // 선언식으로 작성해도 됨
  // function onIncrease() {
  //   setCount(count + 1);
  // }

  const onDecrease = () => {
    setCount(count - 1);
  };
  return (
    <div>
      <h2>{count}</h2>
      <button onClick={onIncrease}>+</button>
      <button onClick={onDecrease}>-</button>
      <OddEvenResult count={count} />
    </div>
  );
};

export default Counter;

 

app.js

function App() {
  console.log("app 실행");
  const counterProps = {
    a: 1,
    b: 2,
    c: 3,
    d: 4,
    e: 4,
    initialValue: 0,
  };
  return (
    <Container>
      <div className="App">
        <Counter {...counterProps} />
      </div>
    </Container>
  );
}
728x90
반응형

'코딩공부 > React' 카테고리의 다른 글

react하면서 만난 오류들  (0) 2022.12.08
React 궁금증  (0) 2022.12.07
SPA, React router  (0) 2022.12.03
리액트 - 3️⃣ (feat. 리액트를 다루는 기술)  (0) 2022.12.02
React - 1️⃣  (0) 2022.10.18