2021년 3월 24일 (React)

Ji Taek Lim·2021년 3월 24일

드디어 리액트를 배운다....

React JS Crash Course 2021

https://www.youtube.com/watch?v=w7ejDZ8SWv8&t=4974s

React JS - React Tutorial for Beginners

https://www.youtube.com/watch?v=Ke90Tje7VS0&t=863s


이렇게 결과가 나온다.

import React, { Component } from "react";

class Counter extends Component {
  state = {
    count: 0,
    tags: ["tag1", "tag2", "tag3"],
  };

  render() {
    return (
      <div>
        <span className={this.getBadgeClasses()}>{this.formatCount()}</span>
        <button className="btn btn-secondary btn-sm">Increment</button>
        <ul>
          {this.state.tags.map((tag) => (
            <li key={tag}>{tag}</li>
          ))}
        </ul>
      </div>
    );
  }

  getBadgeClasses() {
    let classes = "badge m-2 badge-";
    classes += this.state.count === 0 ? "warning" : "primary";
    return classes;
  }

  formatCount() {
    const { count } = this.state;
    return count === 0 ? "Zero" : this.state.count;
  }
}

export default Counter;

그리고 return값에 함수를 넣어줘서 출력을 할 수도 있고

바로 text를 넣어줄수도 있다.

  renderTags() {
    if (this.state.tags.length === 0) return <p>There are no tags!</p>;
    return (
      <ul>
        {this.state.tags.map((tag) => (
          <li key={tag}>{tag}</li>
        ))}
      </ul>
    );
  }
  render() {
    return (
      <div>
        {this.state.tags.length === 0 && "Please create a new tag!"}
        {this.renderTags()}
      </div>
    );

콘서트럭터를 통해서 연결해줄수 있다.

아니면 화살표 함수를 통해서 연결할 수 있다.

  handleIncrement = () => {
    this.setState({ count: this.state.count + 1 });
  };

Passing Event Argument

  handleIncrement = (product) => {
    console.log(product);
    this.setState({ count: this.state.count + 1 });
  };

  doHandleIncrement = () => {
    this.handleIncrement({ id: 1 });
  };

  render() {
    return (
      <div>
        <span className={this.getBadgeClasses()}>{this.formatCount()}</span>
        <button
          onClick={() => this.handleIncrement({ id: 1 })}
          className="btn btn-secondary btn-sm"
        >
          Increment
        </button>
      </div>
    );
  }
onClick={this.doHandleIncrement}

이렇게 해도 되고

onClick={() => this.handleIncrement({ id: 1 })}

이렇게 해도 된다.
  handleIncrement = (product) => {
    console.log(product);
    this.setState({ count: this.state.count + 1 });
  };


 onClick={() => this.handleIncrement(product)};

이렇게 해도 된다.

passing children은 어떻게 해야하지?

        {this.props.children}

  render() {
    return (
      <div>
        {this.state.counters.map((counter) => (
          <Counter key={counter.id} value={counter.value}>
            <h4>Counter #{counter.id}</h4>
          </Counter>
        ))}
      </div>
    );
  };

아 리액트 졸라 어렵네..

profile
임지택입니다.

0개의 댓글