티스토리 뷰

유튜브 강의

생활코딩 React 1

2021bong 2021. 10. 17. 01:38

Node.js설치

 

터미널에서 npm -v 입력해서 설치 확인

 

npm install -g create-react-app

권한이 없으면
sudo npm install create-react-app

설치 에러 뜰 때 참고 : 유저 이름 부분에 내 유저 이름 사용하면 됨

https://stackoverflow.com/questions/55938030/error-eacces-permission-denied-mkdir-when-installing-sth-with-npm/55938343

 

Error: EACCES: permission denied, mkdir when installing sth with npm

Everytime I try to install something with npm (in this case electron-packager) I run into this error. How can I solve this issue? I have already tried to give me access by changing the permissions...

stackoverflow.com

 

 

create-react-app -v 입력해서 설치 확인

 

개발환경을 만들 폴더를 만들고 *폴더이름이 react면 거절당함

터미널에서 해당 경로 설정하고 create-react-app . 으로 프로젝트 생성


에디터의 터미널에서

npm run start

입력

> React 샘플페이지가 열림

*안 열린다면 react프로젝트를 생성한 폴더를 열고 실행


기본 프로젝트 디렉토리 중

public은 index.html이 들어있음

 

index.html에서 중요한 것

id="root"가 있는 태그 안에는 리액트를 통해서 넣은 태그들이 들어있음

 

 

src 디렉토리 안에서 이 태그들을 수정할 수 있음!

 

html을 수정하고 싶다면 index.js 파일을 수정하면 됨!

index.js의 <App /> = import App = App.js는 실제 컴포넌트에 대한 코드들을 가지고 있음

 

파일을 수정하고 저장하면 웹페이지를 자동으로 리로드를 해줌

반드시 하나의 태그 안쪽에 나머지 태그가 있어야함!

 

css를 수정하고 싶다면 index.css 과 App.css파일을 수정하면 됨!


bulid 할 때 (디플로이 할 때)

npm run build

 

명령어를 입력하면 없었던 build라는 디렉토리가 생김

 

실제로 서비스할 때는 build에 있는 파일을 써야한다. 기존 파일을 쓰면 용량이 너무 큼!

최상위 디렉토리를 build로 위치시키면 된다.

 

serve -s build

npx serve -s build

build로 서버를 만드는 명령어

serve : npm을 이용한 간단한 서버

 

주소가 나오고 해당 주소로 들어가면 볼 수 있음!


컴포넌트를 만드는 기본 형태

App.js 파일에서 

class 클래스이름 extends Component {
  render(){
    return (
      <header>
        최소한 한개의 태그로 둘러 쌓여 있어야함
      </header>
    );
  }
}

그리고 컴포넌트를 사용하면 됨

class App extends Component {
  render() {
    return (
      <div className="App">
        <클래스이름></클래스이름>
      </div>
    );
  }
}

위 코드는 자바스크립트와 비슷하지만 유사한 형태 > JSX

 

 

컴포넌트를 더 효율적으로 사용하기

props를 사용해서 속성을 만들어서 효율적으로 사용할 수 있음!

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>
        <Subject title="React" sub="For UI"></Subject>
      </div>
    );
  }
}

현재의 상태를 알아내고, 질문하고, 검색하고, 설명서를 읽으면 독립~

React사이트에서 tutorial > developer tools 크롬 확장프로그램 설치!

현재 리액트로 만들어진 앱의 상태를 확인할 수 있음

개발자도구(F12)에서 Component 탭에 들어가면 react 코드를 볼 수 있음! 실시간으로 수정도 가능


컴포넌트를 파일로 분리하기

// Component.js
import React, { Component } from 'react'; // React 사용시 꼭 넣어줘야하는 코드

class Content extends Component { // 컴포넌트 코드
  render() {
    return(
      <article>
        <h2>{this.props.title}</h2>
        {this.props.desc}
      </article>
    );
  }
}

export default Content; // 다른 위치에서 가져다 쓸 수 있도록 하는 코드
// App.js
import React, { Component } from 'react';
import Content from "./component/Content"; // 컴포넌트를 import 할 수 있도록 하는 코드
import './App.css';

어떤 컴포넌트가 실행될 때 렌더 함수보다 먼저 실행되면서

그 컴포넌트를 초기화시켜주는 코드 기본형태

class App extends Component {
  constructor(props){ // 제일 먼저 실행되서 초기화를 실행
    super(props);
  }
...
}

 

class App extends Component {
  constructor(props){
    super(props);
    this.state = { // state를 설정
      subject:{
        title:'WEB',
        sub:'world wide web'
      }
    }
  }
  render() {
    return (
      <div className="App">
        <Subject title={this.state.subject.title} sub={this.state.subject.sub}></Subject>
        <Subject title="React" sub="For UI"></Subject>
        <TOC></TOC>
        <Content title="HTML" desc="HTML is HyperText Markup Language."></Content>
      </div>
    ); // {}안에 넣어서 사용
  }
}

이 App.js 를 import 해서 사용하는 index.js에서는 이 파일의 state 내용을 알 수가 없음!

state는 외부에서 알 필요가 없음. 내부적으로 사용할 내용은 state를 사용

외부에서 알 필요가 없는 정보를 철저하게 숨기는 것이 좋은 사용성을 만드는 아주 중요한 핵심!


state

상위 컴포넌트의 state 값을 하위 컴포넌트의 props의 값으로 전달하는 것은 얼마든지 가능

 

props는 부모 컴포넌트가 자식 컴포넌트에게 주는 값

자식 컴포넌트는 부모 컴포넌트의 props를 받아오기만 하고 수정은 불가능

 

state는 컴포넌트 내부에서 선언하여 내부적으로 값 변경가능

 

props나 state가 변경되면 render함수가 다시 호출됨

 

여러개의 엘리먼트를 자동으로 생성할 때는 key값을 정해줘야함. 안하면 에러 뜸


리액트에서 이벤트를 설정할 때는 Camel 표기법으로 적어주고 {}를 사용한다

// 옳은 방법
<h1><a href="/" onClick={}>{this.state.subject.title}</a></h1>

// 틀린 방법
<h1><a href="/" onclick="">{this.state.subject.title}</a></h1>

 

debugger가 있는 곳에서 코드를 멈추고 개발자도구 Sources창에서 보기 편하게 해줌

debugger;

크롬 콘솔창 열고 닫기 Esc

 

태그가 가지고 있는 기본 동작을 못하게 하기

e.preventDefault();

 

 

.bind(this)

        <a href="/" onClick={function(e){
          console.log(e);
          e.preventDefault();
          this.state.mode = 'welcome';
        }.bind(this)}>{this.state.subject.title}</a>

함수는 this값을 아무것도 가지지 않음 > undefined

bind함수를 사용해서 this를 넣어주면 App이라고 하는 컴포넌트 자체를 함수 안에 주입해줌 > this가 App컴포넌트가 됨

 

 

setState 사용

        <a href="/" onClick={function(e){
          console.log(e);
          e.preventDefault();
          this.state.mode = 'welcome';
        }.bind(this)}>{this.state.subject.title}</a>

이렇게 사용하면 리액트 몰래 바꾼게 되어서 mode 값은 바뀌겠지만 그에 따른 함수가 실행이 안됨

 

constructor에서 설정한 값 외에 동적으로 state 값을 바꿀 때는 꼭 setState 사용

state가 바뀐걸 리액트가 알도록!

        <a href="/" onClick={function(e){
          console.log(e);
          e.preventDefault();
          this.setState({
            mode:'welcome'
          });
        }.bind(this)}>{this.state.subject.title}</a>

컴포넌트 이벤트 만들기

이벤트를 만들어서 사용할 수 있음!

// Subject.js
<header>
        <h1><a href="/" onClick={function(e){ 
          e.preventDefault(); 
          this.props.onChangePage();
        }.bind(this)}>{this.props.title}</a></h1> // 클릭이벤트 추가, 설정한 이벤트 추가, 바인드this
        {this.props.sub}
      </header>
// App.js
        <Subject 
          title={this.state.subject.title} 
          sub={this.state.subject.sub}
          onChangePage={function(){ // 설정한 이벤트로 모드 변경 실행
            this.setState({mode:'welcome'});
          }.bind(this)}> // 바인드this
        </Subject>

 

값을 받아올때 문자인지 숫자인지 확인 후 변환해서 사용


중요 개념 정리

 

props 변경불가능

state 변경가능

 

상위에서 하위 컴포넌트로 명령할 때 > props사용

하위에서 상위 컴포넌트로 명령할 때 > 이벤트를 사용 > 상위 컴포넌트의 state값 변경

728x90
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함