nextjs,tailwindcss,vercel

[ react , nextJS ] ๋ฆฌ์•กํŠธ ์ปดํฌ๋„ŒํŠธ - props ์™€ children

์ฃผ์˜ ๐Ÿฑ 2024. 6. 8. 01:11
728x90
๋ฐ˜์‘ํ˜•

๋ฆฌ์•กํŠธ ์ปดํฌ๋„ŒํŠธ๊ฐ€ ๊ฐ€์ง„ props, state ๊ฐœ๋…์— ๋Œ€ํ•ด ์•Œ ํ•„์š”๊ฐ€ ์žˆ๋‹ค. 

 

props๋Š” ์ปดํฌ๋„ŒํŠธ ์™ธ๋ถ€์—์„œ ๋ฐ›์„ ์ˆ˜ ์žˆ๋Š” ๊ฐ’, ๋ถ€๋ชจ๋กœ๋ถ€ํ„ฐ ์ž์‹์—๊ฒŒ ๋‹จ๋ฐฉํ–ฅ ๋ฐ์ดํ„ฐ ํ๋ฆ„ ๊ตฌ์กฐ๋ฅผ ๊ฐ€์ง„๋‹ค. 

 

๋ถ€๋ชจ-์ž์‹ ์ปดํฌ๋„ŒํŠธ๊ฐ€ ์•„๋‹Œ๋ฐ ๋ฐ์ดํ„ฐ๋ฅผ ์ „๋‹ฌํ•ด์•ผํ•˜๋Š”๊ฒฝ์šฐ, context๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค. props์“ฐ๊ธฐ ์•Š๊ณ ๋„ ์ปดํฌ๋„ŒํŠธ ์‚ฌ์ด์— ๋ฐ์ดํ„ฐ๋ฅผ ์ „๋‹ฌํ•  ์ˆ˜ ์žˆ๋‹ค. 

state๋Š” ๋‚ด๋ถ€์—์„œ ์ €์žฅํ•˜๋Š” ๋ฐ์ดํ„ฐ์ด๋‹ค. ๋ฐ˜๋“œ์‹œ ํ•ด๋‹น ์ปดํฌ๋„ŒํŠธ ์ž์‹ ๊ณผ ๊ทธ ํ•˜์œ„์—๋งŒ ์˜ํ–ฅ์„ ๋ฏธ์นœ๋‹ค. 


const [count, setCount] = useState(0)

1. make prop, give it a value

< Greeting text={'yo'}/>

 

2. Use prop value

function Gretting(props){

return <h1>{props.text}</h1>

}

*props๋Š” ์˜ค๋ธŒ์ ํŠธ์ž„,๋‹ค๋ฅธ ์ปดํฌ๋„ŒํŠธ๋“ค์—์„œ ๊ฐ’์„ ๋ฐ›์„ ์ˆ˜ ์žˆ์Œ.

 

prop์—๋Š” ์•„๋ฌด๊ฑฐ๋‚˜ ํŒŒ์‹ฑํ•  ์ˆ˜ ์žˆ๋‹ค. 

children prop -

<Parent /> -> expand tags

<Parent>

  <Child /> -- ์ด๊ฒƒ์ด children์ด๋‹ค. 

</Parent>

 

function (Parent(props)){

return <div>{props.children}</div>

}

 

children props๋Š” layout components์—์„œ ์œ ์šฉํ•˜๊ฒŒ ์“ฐ์ž„

 

 

 

์˜ˆ์‹œ์ฝ”๋“œ

<p>์š”์†Œ๊ฐ€ {CHILDREN}์— ์ „๋‹ฌ๋œ๋‹ค. 

ํ›…์„ ์‚ฌ์šฉํ•ด์„œ ๋ณ€๊ฒฝํ•  ์ˆ˜ ์žˆ๋Š”๊ฒƒ์€ ๋‹ค์Œ์— ์‚ดํŽด๋ณด๊ฒ ๋‹ค. 

 


//Container๋Š” ๋นจ๊ฐ„ ๋ฐ•์Šค์•ˆ์— ์ œ๋ชฉ๊ณผ ์ž์‹ ์š”์†Œ๋ฅผ ํ‘œ์‹œํ•œ๋‹ค. 
const Container = (props: {title: string; children: React.ReactElement }) => {
const { titme, children } = props

return (
<div style={{ background:red}}>
<span>{title}</span>

<div>{children}</div>

</div>
)
};

const Parent = () => {
return (
<Container title='Hello'>
<p>๋ฐฐ๊ฒฝ์œผ๋กœ ๋‘˜๋Ÿฌ์Œ“์ธ ๋ถ€๋ถ„</p>
</Container>
)
}

export default Parent;
๋ฐ˜์‘ํ˜•