React

 

vscode  확장 패키지 추가

1. - Auto Import - ES6, TS, JSX, TSX

2. - Reactjs code snippets

3. - ESLint

4. - Prettier - Code formatter

Visual Studio Code 폴더/파일 아이콘 변경하기

 

1. 개발환경

 

수업 소개

 

1.공부 전략

 

2.개발환경의 종류

공식문서 사이트 : https://ko.reactjs.org/

https://ko.reactjs.org/docs/create-a-new-react-app.html#create-react-app

깃 : https://github.com/facebook/create-react-app

웹 리액트 테스트 사이트 

1)https://ko.reactjs.org/redirect-to-codepen/hello-world

2)https://stackblitz.com/edit/react-trmehv

 

 

3.npm을 이용해서 create react app 설치

nodjs : https://nodejs.org/ko/

npm install create-react-app

npm install create-react-app

 


npx create-react-app my-app


npm은 패키지를 관리만 하고 실행은 할 수 없다.
NPM은 패키지를 관리 하지만 패키지를 실행할 수는 없다.
NPM은 그 자체로는 단순히 어떤 패키지도 실행하지 않는다.
NPM은 사실 어떤 패키지도 실행하지 않는다.
NPM을 사용하여 패키지를 실행하려면 package.json파일 에서 해당 패키지를 지정해야 한다.
npx는 npm 패키지 실행기이다.
NPM은 NPX를 실행하기 위한 도구이다.
NPX는 npm 5.2+와 함께 제공된다.


❗️npm 놔두고 yarn 패키지 매니저 사용 이유는?
 yarn의 본질은 node.js 모듈이다.
npm의 장단점
npm은 배포가 쉽고 종속성을 쉽게 해결할 수 있다는 장점이 있지만 패키지가 중복으로 설치될 수 있다는 단점이 있다.
파일이 많은 경우 문제가 된다.
그래서 페이스북의 node_modules를 관리하면서의 불편한 점을 개선하기 위해 Yarn이 탄생되었다.
yarn은 다음과 같은 특징이 있다.
 yarn의 특징
빠르다 : npm3 보다 패키지 설치 속도가 빠르다. (처음 다운로드 시에는 npm과 동일함)
안전성: json 포맷을 사용하지 않는다.
신뢰성 : 오프라인 모드가 가능하다.
 yarn 설치하기
npm 기반 설치 방법
npm install --global yarn
최신 버전은 업데이트 방법
yarn self-update
yarn 초기화 방법
yarn init
yarn을 이용해 패키지를 추가하려면 add 옵션을 이용
yarn add [package-name]@[version-or-tag] [option]
예를 들어 react 패키지를 설치하려면 다음 명령어를 입력
yarn add react

 

다음을 추천

리랙틍 개발 디렉토리를 임의 로 생성 후 해당 디렉토에서 CMD 창을 열고

설치  : yarn add react

설치버전 확인:  create-react-app -V


 

4.create react app을 이용해서 개발환경구축

 

1) 임의  디렉토리  예 react-app 생성한다

2) 해당 디렉토리에서 create-react-app .

 

 

5.샘플 웹앱 실행

 

npm run start

 

 

 

6.JS 코딩하는 법

 

강의 내용 클래스 방식 변경

class App extends Component {
  render() {
    return (
      <div className="App">
        ~
      </div>
    );
  }
}

export default App;

 

 

7.CSS 코딩하는 법

 

 

8.배포하는 법

 

npm run build

 

배포된 리액스  서버 확인

npx serve -s build

 

 

 

 

2. 컴포넌트 제작

 

9.리액트가없다면

pure.html

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>WEB</h1>
    world  wide web!
    <nav>
        <ul>
            <li><a href="1.html">HTML</a></li>
            <li><a href="2.html">CSS</a></li>
            <li><a href="3.html">Javascript</a></li>
        </ul>
    </nav>
    <article>
    <h2>HTML</h2>
        HTML is HyperText Markup Language.
    </article>
</body>
</html>

 

 

 

 

10.컴포넌트 만들기1

 

App.js

import './App.css';
import { Component } from 'react';

class Subject extends Component {
  render() {
    return (
      <header >
        <h1>WEB</h1>
        world  wide web!
      </header >
    )
  }
}
class App extends Component {
  render() {
    return (
      <div className="App">
        <Subject />

        <h1>Hello, React!!</h1>
      </div >
    );
  }
}

export default App;

 

 

 

 

11.컴포넌트 만들기2

 

App.js

import './App.css';
import { Component } from 'react';
class Subject extends Component {
  render() {
    return (
      <header >
        <h1>WEB</h1>
        world  wide web!
      </header >
    )
  }
}

class TOC extends Component {
  render() {
    return (
      <nav>
        <ul>
          <li><a href="1.html">HTML</a></li>
          <li><a href="2.html">CSS</a></li>
          <li><a href="3.html">Javascript</a></li>
        </ul>
      </nav>
    );
  }
}

class Content extends Component {
  render() {
    return (
      <article>
        <h2>HTML</h2>
        HTML is HyperText Markup Language.
      </article>
    );
  }
}

class App extends Component {
  render() {
    return (
      <div className="App">
        <Subject />
        <TOC />
        <Content />
      </div >
    );
  }
}

export default App;

 

 

 

12.props

 

App.js

import './App.css';
import { Component } from 'react';


class TOC extends Component {
  render() {
    return (
      <nav>
        <ul>
          <li><a href="1.html">HTML</a></li>
          <li><a href="2.html">CSS</a></li>
          <li><a href="3.html">Javascript</a></li>
        </ul>
      </nav>
    );
  }
}

class Content extends Component {
  render() {
    return (
      <article>
        <h2>{this.props.title}</h2>
        {this.props.desc}
      </article>
    );
  }
}

class Subject extends Component {
  render() {
    return (
      <header >
        <h1>{this.props.title}</h1>
        {this.props.sub}
      </header >
    )
  }
}

class App extends Component {
  render() {
    return (
      <div className="App">
        <Subject title="WEB" sub="World wide web!" />
        <Subject title="React" sub="For UI" />
        <TOC />
        <Content title="HTML" desc="HTML is HyperText Markup Language." />
      </div >
    );
  }
}

export default App;

 

 

 

13.React Developer Tools

 

 

크롬  개발 툴 설치  : React Developer Tools

 

 

 

 

14.Component 파일로 분리하기

 

TOC.js

import { Component } from 'react';

class TOC extends Component {
    render() {
        return (
            <nav>
                <ul>
                    <li><a href="1.html">HTML</a></li>
                    <li><a href="2.html">CSS</a></li>
                    <li><a href="3.html">Javascript</a></li>
                </ul>
            </nav>
        );
    }
}


export default TOC;

 

 

App.js

import './App.css';
import { Component } from 'react';
import TOC from './components/TOC';
import Content from './components/Content';
import Subject from './components/Subject';




class App extends Component {
  render() {
    return (
      <div className="App">
        <Subject title="WEB" sub="World wide web!" />
        <Subject title="React" sub="For UI" />
        <TOC />
        <Content title="HTML" desc="HTML is HyperText Markup Language." />
      </div >
    );
  }
}

export default App;

 

 

 

3. state

 

15-1.State 소개

 

 

 

 

15-2 State 사용

 

App.js

import './App.css';
import { Component } from 'react';
import TOC from './components/TOC';
import Content from './components/Content';
import Subject from './components/Subject';




class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      subject: {
        title: "state-WEB",
        sub: "www!"
      }
    }
  }

  render() {
    return (
      <div className="App">
        <Subject title="WEB" sub="World wide web!" />
        <Subject title={this.state.subject.title} sub={this.state.subject.sub} />
        <TOC />
        <Content title="HTML" desc="HTML is HyperText Markup Language." />
      </div >
    );
  }
}

export default App;

 

 

 

15-3. key

 

 

App.js

import './App.css';
import { Component } from 'react';
import TOC from './components/TOC';
import Content from './components/Content';
import Subject from './components/Subject';

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      subject: {
        title: "state-WEB",
        sub: "www!"
      },
      content: [
        { id: 1, title: "1.HTML", desc: "HTML is for information" },
        { id: 2, title: "2.CSS", desc: "CSS is for design" },
        { id: 3, title: "3.javaScript", desc: "javaScript is for interactive" },
      ]
    }
  }

  render() {
    return (
      <div className="App">
        <Subject title="WEB" sub="World wide web!" />
        <Subject title={this.state.subject.title} sub={this.state.subject.sub} />
        <TOC data={this.state.content} />
        <Content title="HTML" desc="HTML is HyperText Markup Language." />
      </div >
    );
  }
}

export default App;

 

TOC.js

import { Component } from 'react';

class TOC extends Component {

    render() {

        let lists = [];
        const data = this.props.data;
        let i = 0;
        while (i < data.length) {
            lists.push(
                <li key={data[i].id}><a href={"/content/" + data[i].id}>{data[i].title}</a></li>
            );
            i = i + 1;
        }

        return (
            <nav>
                <ul>
                    {lists}
                </ul>
            </nav>
        );
    }
}


export default TOC;

 

 

 

 

 

 

 

 

4. 이벤트

 

 

16-1. 이벤트 state props 그리고 render 함수

 

App.js

import './App.css';
import { Component } from 'react';
import TOC from './components/TOC';
import Content from './components/Content';
import Subject from './components/Subject';

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      mode: "read",
      subject: { title: "WEB", sub: "www!" },
      welcome: { title: "welcome", desc: "Hello, React!!" },
      content: [
        { id: 1, title: "1.HTML", desc: "HTML is for information" },
        { id: 2, title: "2.CSS", desc: "CSS is for design" },
        { id: 3, title: "3.javaScript", desc: "javaScript is for interactive" },
      ]
    }
  }

  render() {
    console.log("App render");
    let _title, _desc = null;
    if (this.state.mode === "welcome") {
      _title = this.state.welcome.title;
      _desc = this.state.welcome.desc;

    } else if (this.state.mode === "read") {
      _title = this.state.content[0].title;
      _desc = this.state.content[0].desc;
    }


    return (
      <div className="App">

        <Subject title={this.state.subject.title} sub={this.state.subject.sub} />
        <TOC data={this.state.content} />
        <Content title={_title} desc={_desc} />
      </div >
    );
  }
}

export default App;

 

 

 

 

16-2. 이벤트 

 

 

App.js

~

 return (
      <div className="App">
        {/* <Subject title={this.state.subject.title} sub={this.state.subject.sub} /> */}
        <header >
          <h1><a href="/" onClick={
            function (e) {
              console.log(e);
              //debugger;
              e.preventDefault();
              //alert("hi");
            }
          }>{this.state.subject.title}</a></h1>
          {this.state.subject.sub}
        </header >

        <TOC data={this.state.content} />
        <Content title={_title} desc={_desc} />
      </div >
    );

~

 

 

 

16-3. 이벤트에서 state 변경하기

 

함수 안에 this. 함수 내에서 this  나타 내므로  오류, 따라서

bind(this) 추가 해주므로서 컴포넌트 내의 this 를 찾게 된다.

 

react 에서 데이터 변경은 setState  형태

       function (e) {
              console.log(e);
              //debugger;
              e.preventDefault();
              //alert("hi");
              //this.state.mode = "welcome";
              this.setState({
                mode: "welcome"
              })

            }.bind(this)

 

 

 

 

16-4. 이벤트 bind 함수 이해하기

 

bind() 메소드가 호출되면 새로운 함수를 생성합니다. 받게되는 첫 인자의 value로는 this 키워드를 설정하고, 이어지는 인자들은 바인드된 함수의 인수에 제공됩니다.

const appDiv = document.getElementById('app');

const obj = { name: 'egoing' };
function bindTest(arg1, arg2) {
  console.log(this.name);
  appDiv.innerHTML = this.name;
  console.log(arg1, arg2);
}
const bindTest2 = bindTest.bind(obj, 'test1', 'test2');
bindTest2();

 

콘솔 출력

egoing
test1 test2

 

 

 

16-5. 이벤트 setState 함수 이해하기

 

생성자에서는 this.state 와 같이 직접변경이 가능하나

 constructor(props) {
    super(props);
    this.state = {
      mode: "read",
      subject: { title: "WEB", sub: "www!" },
      welcome: { title: "welcome", desc: "Hello, React!!" },
      content: [
        { id: 1, title: "1.HTML", desc: "HTML is for information" },
        { id: 2, title: "2.CSS", desc: "CSS is for design" },
        { id: 3, title: "3.javaScript", desc: "javaScript is for interactive" },
      ]
    }
  }

 

그 외에서는 react 는 setState  형식으로 데이터를 변경해야 한다.

 //this.state.mode = "welcome";
              this.setState({
                mode: "welcome"
              })

 

 

 

17-1. 컴포넌트 이벤트 만들기 1

 

임의 함수 onChangePage1  생성 후  자식 컴포넌트에서 this.props.onChangePage1(); 로 호출이 가능하다.

 

 

App.js

~ 
<Subject
          title={this.state.subject.title}
          sub={this.state.subject.sub}
          onChangePage1={function () {
            alert("hihihi1");
            this.setState({
              mode: "welcome"
            })
          }.bind(this)}
 /> 
~

 

 

Subject.js

import { Component } from 'react';

class Subject extends Component {
    render() {
        console.log("Subject render");
        return (
            <header >
                <h1><a href="/" onClick={function (e) {
                    e.preventDefault();
                    this.props.onChangePage1();
                }.bind(this)} >{this.props.title}</a></h1>
                {this.props.sub}
            </header >
        )
    }
}

export default Subject;

 

 

 

 

 

17-2. 컴포넌트 이벤트 만들기 2

 

App.js

~
 <TOC onChangePage={function (e) {
          //console.log(e);
          this.setState({ mode: "read" });

        }.bind(this)} data={this.state.content} />

~

 

Toc.js

import { Component } from 'react';

class TOC extends Component {

    render() {
        console.log("TOC render");
        let lists = [];
        const data = this.props.data;
        let i = 0;
        while (i < data.length) {
            lists.push(
                <li key={data[i].id}><a href={"/content/" + data[i].id}
                    onClick={function (e) {
                        e.preventDefault();
                        //console.log(e.target.innerText);
                        this.props.onChangePage(e.target.innerText);
                    }.bind(this)}
                >{data[i].title}</a></li>
            );
            i = i + 1;
        }

        return (
            <nav>
                <ul>
                    {lists}
                </ul>
            </nav>
        );
    }
}


export default TOC;

 

 

 

 

17-3. 컴포넌트 이벤트 만들기 3

 

자식 컴포넌트에서 부모컴포넌트에 데이터를 넘겨주는 방법은 다음과 같이 이벤트 로 넘겨준다.

부모 컴포넌트

  <TOC onChangePage={function (id) {
          //console.log("event :", id);
          this.setState({
            mode: "read",
            selected_content_id: Number(id)
          });

 

자식컴포넌트

              <li key={data[i].id}><a href={"/content/" + data[i].id}
                    data-id={data[i].id}
                    onClick={function (id, e) {
                        e.preventDefault();
                        //const id = e.target.dataset.id;
                        console.log("id : ", id);
                        //this.props.onChangePage(id);
                        //bind 에 파라미터 값을 추가하면 this event 값은 한칸씩 뒤로 밀린다.
                    }.bind(this, data[i].id)}
                >{data[i].title}</a></li>

 

 

 

App.js

import './App.css';
import { Component } from 'react';
import TOC from './components/TOC';
import Content from './components/Content';
import Subject from './components/Subject';

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      mode: "read",
      selected_content_id: 2,
      subject: { title: "WEB", sub: "www!" },
      welcome: { title: "welcome", desc: "Hello, React!!" },
      contents: [
        { id: 1, title: "1.HTML", desc: "HTML is for information" },
        { id: 2, title: "2.CSS", desc: "CSS is for design" },
        { id: 3, title: "3.javaScript", desc: "javaScript is for interactive" },
      ]
    }
  }

  render() {
    // console.log("App render");
    let _title, _desc = null;
    if (this.state.mode === "welcome") {
      _title = this.state.welcome.title;
      _desc = this.state.welcome.desc;

    } else if (this.state.mode === "read") {
      // let i = 0;
      // while (i < this.state.contents.length) {
      //   const data = this.state.contents[i];
      //   if (this.state.selected_content_id === data.id) {
      //     console.log("data", data);
      //     _title = data.title;
      //     _desc = data.desc;
      //     break;
      //   }
      //   i++;
      // }

      const data = this.state.contents.filter(item => {
        return this.state.selected_content_id === item.id
      })[0];
      // console.log("data", data);
      _title = data.title;
      _desc = data.desc;
    }

    return (
      <div className="App">
        <Subject
          title={this.state.subject.title}
          sub={this.state.subject.sub}
          onChangePage1={function () {
            alert("hihihi1");
            this.setState({
              mode: "welcome"
            })
          }.bind(this)}
        />
        <TOC onChangePage={function (id) {
          //console.log("event :", id);
          this.setState({
            mode: "read",
            selected_content_id: Number(id)
          });


        }.bind(this)} data={this.state.contents} />
        <Content title={_title} desc={_desc} />
      </div >
    );
  }
}

export default App;

 

TOC.js

import { Component } from 'react';

class TOC extends Component {

    render() {
        // console.log("TOC render");
        let lists = [];
        const data = this.props.data;
        let i = 0;
        while (i < data.length) {
            lists.push(
                <li key={data[i].id}><a href={"/content/" + data[i].id}
                    data-id={data[i].id}
                    onClick={function (id, e) {
                        e.preventDefault();
                        //const id = e.target.dataset.id;
                        console.log("id : ", id);
                        //this.props.onChangePage(id);
                        //bind 에 파라미터 값을 추가하면 this event 값은 한칸씩 뒤로 밀린다.
                    }.bind(this, data[i].id)}
                >{data[i].title}</a></li>
            );
            i = i + 1;
        }

        return (
            <nav>
                <ul>
                    {lists}
                </ul>
            </nav>
        );
    }
}


export default TOC;

 

 

 

 

 

 

 

React - 생활코딩 2

 

 

 

 

소스 :  https://github.com/braverokmc79/LifeCoding

 

 

 

about author

PHRASE

Level 60  라이트

높은 지위는 위대한 사람을 더욱 위대하게 하고 작은 인물은 더욱 작게 한다. -라 브뤼에르

댓글 ( 4)

댓글 남기기

작성