[๐Ÿ’ŽReact] ๋ฆฌ์•กํŠธ์—์„œ ๋™์ ์ธ UI ๋งŒ๋“œ๋Š” ๋ฐฉ๋ฒ•

h-a-n-aยท2023๋…„ 3์›” 7์ผ
1

๐Ÿ’ŽReact

๋ชฉ๋ก ๋ณด๊ธฐ
5/14

props

๋ถ€๋ชจ component์—์„œ ์“ฐ๋˜ state๋ฅผ ์ž์‹์—๊ฒŒ ์ „์†กํ•˜๋Š” ๋ฐฉ๋ฒ•

์ฃผ์˜*
๋ถ€๋ชจ -> ์ž์‹ ์ปดํฌ๋„ŒํŠธ๊ฐ„์—๋งŒ ๊ฐ€๋Šฅ
โŒ ์ž์‹ -> ๋ถ€๋ชจ ๋ถˆ๊ฐ€๋Šฅ โŒ
โŒ ํ˜•์ œ๋ผ๋ฆฌ ์ปดํฌ๋„ŒํŠธ๊ฐ„์—๋„ ๋ถˆ๊ฐ€๋Šฅ โŒ

์‚ฌ์šฉ๋ฒ•

  1. ๋ถ€๋ชจ์ปดํฌ๋„ŒํŠธ์—์„œ <์ž์‹์ปดํฌ๋„ŒํŠธ ์–ด์ฉŒ๊ตฌ์ €์ฉŒ๊ตฌ={์‚ฌ์šฉํ•  state์ด๋ฆ„}/>
  2. ์ž์‹์ปดํฌ๋„ŒํŠธ์—์„œ ํŒŒ๋ผ๋ฏธํ„ฐ์— props ์ ์–ด์ฃผ๊ธฐ(๊ด€์Šต์ ์œผ๋กœ props๋ผ๊ณ  ์”€)
  3. ์ž์‹์ปดํฌ๋„ŒํŠธ์—์„œ props ์‚ฌ์šฉํ•  ๋ถ€๋ถ„์— {props.์–ด์ฉŒ๊ตฌ์ €์ฉŒ๊ตฌ} ์“ฐ๊ธฐ
    ๊ทผ๋ฐ, ๋ณดํ†ต ์–ด์ฉŒ๊ตฌ์ €์ฉŒ๊ตฌ๋ถ€๋ถ„์€ ์‚ฌ์šฉํ•  state์ด๋ฆ„๊ณผ ๋™์ผํ•˜๊ฒŒ ์ ์Œ

๊ทผ๋ฐ ์ด๊ฑฐ ๋ฐ˜๋“œ์‹œ state๋งŒ ์ „์†กํ•  ์ˆ˜ ์žˆ๋Š”๊ฑด ์•„๋‹ˆ๋ผ๊ณ  ํ•œ๋‹ค

ํ•จ์ˆ˜ ํŒŒ๋ผ๋ฏธํ„ฐ ๋ฌธ๋ฒ•์ด๋ž‘ ๋˜‘๊ฐ™์ด, props ํ•˜๋‚˜ ๋งŒ๋“ค๊ณ  ๊ทธ ์ž๋ฆฌ์— ์ด๊ฒƒ๋„ ๋„ฃ์–ด๋ณด๊ณ  ์ €๊ฒƒ๋„ ๋„ฃ์–ด๋ณด๋ฉฐ ๋น„์Šทํ•œ ์ปดํฌ๋„ŒํŠธ ์—ฌ๋Ÿฌ๊ฐœ ๋งŒ๋“œ๋Š” ๊ฒƒ๋„ ๊ฐ€๋Šฅ!!?!

import {useState} from 'react'
function App(){
let [food,setFood]=useState(['์šฐ๋™','๊น€๋ฐฅ'])
return(
<div>
<Food food={food}/>
<Food food="์•ˆ๋…• ๋‚˜๋Š” ํ”„๋กญ์Šค์•ผ"/>
<Food food={food} color="orange"/>
</div>
)
}
function Food(props){
return(
<div style={{backgroundColor:props.color}}>
<h4>{props.food}</h4>
</div>
)
}

๋™์ ์ธ UI ๋งŒ๋“œ๋Š” ๋ฒ•

์‚ฌ์šฉ์ž๊ฐ€ ์กฐ์ž‘ํ•  ๋•Œ ํ˜•ํƒœ๊ฐ€ ๋ฐ”๋€Œ๋Š” ๋ชจ๋‹ฌ์ฐฝ, ํƒญ, ์„œ๋ธŒ๋ฉ”๋‰ด, ํˆดํŒ, ๊ฒฝ๊ณ ๋ฌธ ๋“ฑ๋“ฑ์˜ UI๋“ค

1.html css ๋กœ ๋ฏธ๋ฆฌ ๋””์ž์ธํ•ด๋‘”๋‹ค

2.ํ˜„์žฌ UI ์ƒํƒœ๋ฅผ state๋กœ ๋งŒ๋“ค์–ด๋‘”๋‹ค

3. state ์ข…๋ฅ˜์— ๋”ฐ๋ผ์„œ UI๊ฐ€ ์–ด๋–ป๊ฒŒ ๋ณด์ผ์ง€ ์ž‘์„ฑํ•œ๋‹ค

์—ฐ์Šต

์šฐ๋™/๊น€๋ฐฅ/๋ˆ๊นŒ์Šค ๋ˆ„๋ฅด๋ฉด ์•„๋ž˜์— ๋นจ๊ฐ•/๋…ธ๋ž‘์นธ์—๋„ ํ•ด๋‹น๊ธ€์ž๊ฐ€ ๋œจ๊ฒŒ ํ•˜๊ณ  ์‹ถ๋‹ค.

function App(){
const [food,setFood] = useState(["์šฐ๋™", "๊น€๋ฐฅ", "๋ˆ๊นŒ์Šค"]);
const [title, setTitle] = useState(0);
return(
<div>
 {food.map((a, i) => {
        return (
          <div>
            <h4
              onClick={() => {
                setTitle(i);
              }}
            >
              {a}
            </h4>
          </div>
        );
      })}
      <FoodModal food={food} title={title}/>
</div>
}

function FoodModal(props){
return(
<div>
<h4>{props.food[props.title]}</h4>
</div>)
}

์ง  ์™„์„ฑ์“ฐ

profile
ํ•˜๋ฃจํ•˜๋ฃจ๊ฐ€ ์—ฐ์Šต์ด๋‹ˆ ๋‚ด์ผ์€ ๋” ๊ฐ•ํ•ด์งˆ ๊ฒ๋‹ˆ๋‹ค

0๊ฐœ์˜ ๋Œ“๊ธ€