공부/Next.js

next.js - 부모에서 자식으로 데이터 전달 (props)

딸기버블티 2024. 4. 18. 22:57

page.js

export default function Cart() {
  let 장바구니 = ['Tomatoes', 'Pasta'];
    return (
      <div>
        <h4 className="title">Cart</h4>
        <CartItem item={장바구니[0]}/>
        <CartItem item={장바구니[1]}/>
        <Banner content="롯데카드"/>
        <Banner content="삼성카드"/>
      </div>
    )
  } 

  function Banner(props){
    return <h5>{props.content} 결제 행사중</h5>
  }
  
  function CartItem(props){
    return (
        <div className="cart-item">
          <p>{props.item}</p>
          <p>$40</p>
          <p>1개</p>
        </div>
    )
  }

 

Cart 부모에서 CartItem 으로 [장바구니] 라는 데이터를 전달

<컴포넌트명 변수명={전달할 데이터}/> 로 사용

자식 펑션에서는 함수 데이터 받듯이 props 를 적어주고

자식 펑션 안에서 props.변수명 으로 사용

 

자식에서 부모로는 전송 불가

자식에서 자식으로도 전송 불가

 

 

 

+ css

import { Component } from "react"

export default function Cart() {
  let 장바구니 = ['Tomatoes', 'Pasta'];
  return (
    <div>
      <h4 className="title">Cart</h4>
      <RedButton color='blue' />
    </div>
  )
}

function RedButton(props) {
  return (
    <button style={{ backgroundColor: props.color, width: '30px', height: '30px' }}></button>
  )
}