Props를 통해 컴포넌트간 데이터 전달하기

Dev_Go·2023년 9월 22일
0

React basic

목록 보기
7/12
post-thumbnail
  1. 가짜데이터 만들기
    현재 UI를 위해 필요한 컴포넌트들을 생성해 놓았습니다.
    그래서 가짜 데이터를 생성한 후에 그 가짜 데이터를 이용해서 지출 리스트를 보여주겠습니다.

  2. Props

  • Props는 Properties의 줄임말
  • Props는 상속하는 부모 컴포넌트로부터 자녀 컴포넌트에 데이터 등을 전달하는 방법
  • Props는 읽기 전용(immutable)으로 자녀 컴포넌트 입장에서는 변하지 않는다.(변하게 하고자 하면 부모 컴포넌트에서 state를 변경시켜줘야한다.)

부모 컴포넌트

import { Component } from "react";
import "./App.css";
import ExpenseForm from "./components/ExpenseForm";
import ExpenseList from "./components/ExpenseList";

class App extends Component {
  // 부모컴포넌트 배열
  initialExpenses = [
    { id: 1, charge: "렌트비", amount: 1600 },
    { id: 2, charge: "교통비", amount: 400 },
    { id: 3, charge: "식비", amount: 1200 },
  ];
  render() {
    return (
      <main className="main-container">
        <h1>예산 계산기</h1>

        <div style={{ width: "100%", backgroundColor: "white", padding: "1rem" }}>
          {/* {Expense From} */}
          <ExpenseForm />
        </div>
        <div style={{ width: "100%", backgroundColor: "white", padding: "1rem" }}>
          {/* {Expense List} */}
          {/* 자식 컴포넌트에 배열 보내기 */}
          <ExpenseList initialExpenses={this.initialExpenses} />
        </div>
        <div style={{ display: "flex", justifyContent: "end", marginTop: "1rem" }}>
          <p style={{ fontSize: "2rem" }}>
            총지출:
            <span></span>
          </p>
        </div>
      </main>
    );
  }
}

export default App

자식 컴포넌트

console.log(this.props.initialExpenses);

콘솔창

profile
프론트엔드 4년차

0개의 댓글