React 시작!

YEONGHUN KO·2022년 1월 22일
0

REACT JS - BASIC

목록 보기
1/30
post-thumbnail

그렇다. 페이스북에서 밀어주고 있는 그 유명한 React맞다. 바닐라로 손수 컴포넌트를 만들어서 프로젝트를 여러개 해보았다. state , rendering, import에 대한 개념이 어느정도 잡혀서 이제 React로 넘어가도 될 수 있을거 같다는 생각이 들었다.

그래서 our lovely Colt에게 리액트를 배우기 시작했는데 진짜 정말 신기한 기능들이 있어서 잠깐 정리해보려고 한다.

Component

  • Building block of React
  • Combines logic (JS) and presentaion(JSX)
import React, { Component } from 'react';

import PokeGames from './PokeGames';

class App extends Component {
  render() {
    // PokeGames 컴포넌트를 아래와 같이 사용가능
    return <PokeGames />;
  }
}

조립 부품이라고 생각하면 쉽다.

Props(Properties)

  • It is already built inside class component
  • Data passed to a component (or found via defaults)
  • Immutablel; component cannot change its own props
//Pokedex.js
<Pokecard
    key={id}
    id={this.handleId(id)}
    name={name}
    type={type}
    base_experience={base_experience}
/>

//Pokecard.js
render() {
    const { id, name, type, base_experience } = this.props;
    return (
        <div className="Pokecard">
        <h2>{name}</h2>
        <div className="img-container">
            <img
            src={`https://assets.pokemon.com/assets/cms2/img/pokedex/detail/${id}.png`}
            alt={name}
            />
        </div>

        <div className="Pokecard__info">
            <span>Type: {type}</span>
            <span>EXP: {base_experience}</span>
        </div>
        </div>
    );
}

// defaultProps
class blah extends Component {
    static defaultProps = {
    pokemons: [
      { id: 4, name: 'Charmander', type: 'fire', base_experience: 62 },
      { id: 7, name: 'Squirtle', type: 'water', base_experience: 63 },
      { id: 11, name: 'Metapod', type: 'bug', base_experience: 72 },
      { id: 12, name: 'Butterfree', type: 'flying', base_experience: 178 },
      { id: 25, name: 'Pikachu', type: 'electric', base_experience: 112 },
      { id: 39, name: 'Jigglypuff', type: 'normal', base_experience: 95 },
      { id: 94, name: 'Gengar', type: 'poison', base_experience: 225 },
      { id: 133, name: 'Eevee', type: 'normal', base_experience: 65 },
    ],
  };

  this.props.pokemons
}

컴포넌트를 만들고 로그해보면 안에 props가 원래 포함되어있다는 걸 알 수 있다.
보면 props를 상위 컴포넌트에서 넘겨줄 수 있다(argument 처럼, html attribute처럼 보이긴 하지만).
그럼 Pokecard에서 넘겨받아서 사용가능하다. 그리고 defaultProps을 세팅가능하다.
단!, 이름은 반드시 defaultProps 이어야 한다(not arbitrary name!)

State

  • internal data specific to a component
  • data that changes over time!
class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      score: 0,
      name: 'Yeong',
    };
  }

  render() {
    return (
      <div>
        <p>Your score is: {this.state.score}</p>
      </div>
    );
  }
}

props와는 다르게 바꿀 수 있다.

또한 constructor안에 super를 통해서 Component 클래스에 props를 넘겨줘야 constructor안에서 this.state , this.props를 사용할 수 있다.(참고로 this.props는 constructor가 아닌 다른 메소드에서는 자동으로 사용가능하다.) 그리고 그렇게 해야만, React 컴포넌트로 등록이 된다.

Component(부모 class)에서 props를 받아서 constructor안에서 사용하게끔하는 로직이 있을거다.

react magic은 babel try it out 에서 확인해보자.

그리고 state를 주먹구구식으로 바꾸지 말고 리액트에서 제공하는 setState라는 built-in 메소드를 이용하자. setState는 비동기적으로 state를 업데이트한다음 다시 DOM을 랜더링한다. 가장 최적의 타이밍을 찾기 위해서 비동기적 랜더링을 한다.

질문: react에서 event 등록 할때 this가 undefined됨

handleClick(e) {
  console.log(e); // SyntheticBaseEvent(리액트에서 만든 이벤트인것 같음)
  console.log(this); // undefined
}

render() {
  return (
    <div>
      <p>{this.state.isClicked ? 'Clicked!!' : 'Not clicked!!'}</p>
      <button onClick={this.handleClick}>Click</button>
    </div>
  );
}
  • bind를 통해서 예방할 수 있다. 근데 this가 button인 줄 알았는데, 아니 적어도 window일줄 알았는데 undefined된다?? react에서 뭘 했길래...헷갈린다..

이에 대한 포스팅은 다음에 하도록 하겠다

profile
'과연 이게 최선일까?' 끊임없이 생각하기

0개의 댓글