2022년 7월 21일 목요일

[패스트캠퍼스] react 강의 학습일지 - 6주차, React

React&Redux로 시작하는 웹프로그래밍_6주차


* 참고 웹사이트 *


React 연습할때 유용한 사이트

codesandbox 

주소: https://codesandbox.io/
사용법: create sandbox: official static에서 static 선택하기

w3schools.com : 바닐라js 연습

React 정보를 찾을때 유용한 사이트
MDN
(공식문서) 웹표준 문서

React의 CDN (Content Delivery Network)
(공식문서) 웹에서 사용되는 다양한 컨텐츠/리소스를 저장하여 제공하는 시스템
검색: react document cdn



DOM / Element

element는 사용자 눈에 보여지는 것, DOM은 컴퓨터/브라우저가 이해하는 element의 원형


바닐라js vs. react 비교

순수 자바스크립트 = 바닐라 라고함. 

바닐라를 사용한 코드
<!DOCTYPE html>
<html lang="en">
<body>
<script src="https://unpkg.com/react@18/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>/script>
  <div id="root"></div>
  <script>
    const rootElement = document.getElementById("root");
    const elementV = document.createElement("h1");
    elementV.textContent = "Hello, World!";
    rootElement.appendChild(elementV);
  </script>  
</body>
</html>

리액트를 사용한 코드
*render 방식이 바뀜
https://ko.reactjs.org/blog/2022/03/08/react-18-upgrade-guide.html
<!DOCTYPE html>
<html lang="en">
<body>
  <script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
  <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
  <div id="root"></div>
  <script>
    const rootElement = document.getElementById("root");
    const root = ReactDOM.createRoot(rootElement);
    //const elementV = document.createElement("h1");
    //elementV.textContent = "Hello, World!";
    const element = React.createElement("h1", { children: "Hello, World!"});
    //rootElement.appendChild(elementV);
    root.render(element);
  </script>  
</body>
</html>

차이
    //chrome 개발자 도구에서 console을 열면, 구조가 다른것을 확인할 수 있다
    console.log(elementV);
    console.log(element); //리액트가 객체를 생성함



JSX문법 & Babel

JSX: 문자도 HTML도 아닌 JavaScript의 확장 문법
Babel (바벨): 자바스크립트 컴파일러 (https://babeljs.io/)
(컴파일러: 언어해석기, 특정 언어를 다른 프로그래밍 언어로 옮기는 프로그램)

즉, Javascript가 JSX를 이해할 수 있도록 바벨을 사용함.

Unpkg을 이용해 Babel 연결하는 방법: 주소 찾아서 연결하기
검색방법: babel unpkg cdn link 구글링


  <!-- Load Babel -->
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
 
  <div id="root"></div>

  <!-- Your custom script here -->
  <script type="text/babel">
    //변수를 직접 html에 넣는다. 모든것을 함수/변수화할수 있는것이 JSX의 장점
    const rootElement = document.getElementbyId("root");

    const text = "hello World!";
    const titleClassName = "title12";
    const customH1 = <h1 className={titleClassName}>[text]</h1>;
    const customH2 = <h1 className={titleClassName} children={text}></h1>;
    const customH2 = <h1 className={titleClassName} children={text} />;

    //spread 연산자
    const props = { className: titleClassName, children: text };
    const customH3 = <h1 {...props} />; //아래와 동일
    const customeH3 = {
      <h1 className={props.className} children={props.children} />
    };
    const element = customH1;

    ReactDOM.render(element, rootElement);

  </script>


  <div id="root">
    <h1>HELLO</h1>
    <h3>World!</h3>
    <h5>BYE BYE</h5>
  </div>

  <script>

    //멀티 elements 생성 , 재 사용 가능
    const rootElement = document.getElementbyId("root");

    const element = (
      <React.Fragment
        className="box"
        children={[
          React.createElement{"h1", null, "Hi"},
          React.createElement{"h3", null, "bye"},
          React.createElement{"h5", null, "World"},
        ]}
      />
      );

    const element1 = (
      <React.Fragment
        className="box"
        children={[<h1>hi</h1>, <h3>bye</h3>, <h5>world</h5>]}

        // children={[
        //   <h1>hi</h1>,
        //   <h3>bye</h3>,
        //   <h5>world</h5>
        //]}
      />
    );

   
    const element2 = (
      <React.Fragment>  
        <h1>hi</h1>
        <h3>bye</h3>
        <h5>world</h5>
      </React.Fragment>
    );

    //<React.Fragment> 생략가능
    const element2 = (
      <>
        <h1>hi</h1>
        <h3>bye</h3>
        <h5>world</h5>
      </>
    );

    ReactDOM.render(element, rootElement);
    ReactDOM.render(element1, rootElement);
    ReactDOM.render(element2, rootElement);

  </script>  


<!-- Custome Element -->
<div id="root"></div>

<script>

  //찍어내기
  const rootElement = document.getElementbyId("root");
  const paint = (title, description) => {
    <>
      <h1>{title}</h1>
      <h5>{descriptiton}</h5>
    </>
  };

  const element = {
    <>
      {paint("title1","normal")}
      {paint("title2","hard")}
      {paint("title3","extream")}
    </>
  };

  ReactDOM.render(paint(), rootElemnet);

</script>  


<script>

  //위와 같은 코드, children 추가 (갯수 무제한)
  const rootElement = document.getElementbyId("root");
  const Paint = (title, description, children) => {
    <>
      <h1>{title}</h1>
      <h5>{descriptiton}</h5>
      {children}
    </>
  };

  const element = {
    <>
      <Paint title="title1" description="normal">
        <h1>Children is here</h1>
      </Paint>
      <Paint title="title2" description="hard" />
      <Paint title="title3" description="extream" />
    </>
  };

  ReactDOM.render(paint(), rootElemnet);

</script>  



리액트의 리랜더링

바닐라 JS 는 변경으로 인해 Element를 다시 그리고, React는 변경된 부분만 다시그린다.

//바닐라 JS는 버튼 자체를 새로 만들지만, React는 숫자만 변경하고 버튼은 그대로 놔둔다.

  <!-- // 바닐라 JS -->
  <script>

    const rootElement = document.getElementbyId("root");

    function random() {
      const number = Math.floor(Math.random() * (10-1)+1 );
      const element = `
      <button>${number}</button>
      `;
      rootElemnt.innerHTML = element;
    }

    setInterval(random, 1000); //1초마다 random 함수를 계속 불러와라

  </script>

    <!-- //Babel -->
    <script type="text/babel">
      const rootElement = document.getElementbyId("root");

      function random() {
        const number = Math.floor(Math.random() * (10-1)+1 );
        const element = <button>${number}</button>;
        ReactDOM.render(element, rootElement);
      }

      setInterval(random, 1000); //1초마다 random 함수를 계속 불러와라

  </script>


이벤트 핸들러 써보기

React: on{Event} (카멜 케이스로 프롭스 전달하기)


컴포넌트 상태 / 사이드이펙트

컴포넌트: 앨리먼트의 집합
상태: useState 상태값을 관리해주는 hook
사이드이펙트: 부수적인 효과를 낼때 사용

Hook
커스텀 훅
반복: 함수로 작성
hook들이 반복은 custom Hook으로 이용해서 상태관리하기
이름정할때, use+카멜케이스 이름

Hook Flow
훅들의 호출 타이밍

Form
* 예제 참고 하기


Error
* 예제 참고하기







#패스트캠퍼스 #내일배움카드 #국비지원 #K디지털기초역량훈련 #바이트디그리 #react강의

댓글 없음:

댓글 쓰기