개발/🟦 React

[문법] 파라미터(props) 사용 (부모 -> 자식) 1

비니_ 2025. 1. 16. 19:12
728x90

📌 부모 -> 자식 state 전송 방법

1. <자식컴포넌트 작명={부모컴포넌트의 state명} />
2. 자식컴포넌트에서 props(파라미터)로 받아서 사용 -> {props.작명}

 

❗❕ 중요 ❗❕ 

부모 -> 자식 가능⭕

자식 -> 부모 불가능❌

친구 -> 친구 불가능❌

 

 

코드 👇

import { useState } from 'react'
import './App.css'

function App() {
  let [구이름, 구이름변경] = useState(['강남구', '송파구', '서초구']);
  let [modal, setModal] = useState(false);

  return (
    <>
      <div>
        <button onClick={() => {
          setModal(!modal);
        }}>모달창</button>

        {modal === true ? <Modal 구이름={구이름[0]}/> : null}
      </div>
    </>
  )
}

function Modal(props){
  return(
    <>
    <div className="modal">
      <h2>{props.구이름}</h2>
      <p>날짜</p>
      <p>상세내용</p>
    </div>
    </>
  )
}

export default App;

 

 

결과 👇

 

 

 

 

✔ 여러개 모달에 각각 className 넣기

{modal === true ? <Modal 구이름={구이름[0]} className="bg_yellow"/> : null}
<div className={`modal ${props.className}`}>

 

코드 👇

function App() {
  let [구이름, 구이름변경] = useState(['강남구', '송파구', '서초구']);
  let [modal, setModal] = useState(false);

  return (
    <>
      <div>
        <button onClick={() => {
          setModal(!modal);
        }}>모달창</button>

        {modal === true ? <Modal 구이름={구이름[0]} className="bg_yellow"/> : null}
        {modal === true ? <Modal 구이름={구이름[1]} className=""/> : null}
      </div>
    </>
  )
}

function Modal(props){
  return(
    <>
    <div className={`modal ${props.className}`}>
      <h2>{props.구이름}</h2>
      <p>날짜</p>
      <p>상세내용</p>
    </div>
    </>
  )

 

결과 👇

728x90