생활코딩 독학/WEB2 - JS React
React #4 props
codingfeature
2023. 1. 10. 10:48
props 란 컴포넌트의 입력값(속성).
<Header title="WEB"></Header>
WEB을 속성값으로 컴포넌트에 넘겨주고 싶다면
function Header(props){
return <header>
<h1><a href="/">{props.title}</a></h1>
</header>
}
함수 인자를 props로. (대부분 props라고 작성.)
props는 객체.
이때 props.title을 '{', '}'로 감싸줘서 사용.
예를 들어
<li><a href="/read/1">html</a></li>
<li><a href="/read/2">css</a></li>
<li><a href="/read/3">js</a></li>
과 같이 리스트 작성 시,
먼저,
const topics = [
{id:1, title:'html', body:'html is ...'},
{id:2, title:'css', body:'css is ...'},
{id:3, title:'javascript', body:'javascript is ...'}
]
topics 배열을 선언,
id, title, body 정보를 객체 구조로 선언하고
App(){}의 return 내
<Nav topics={topics}></Nav>
를 작성하여 topics 배열을 보낸다.
그 후,
function Nav(props){
var lis = []
for(let i=0; i<props.topics.length; i++){
let t = props.topics[i];
lis.push(<li key={t.id}><a href={'/read/'+t.id}>{t.title}</a></li>)
}
return <nav>
<ol>
{lis}
</ol>
</nav>
}
이런 식으로 작성 시,
key는 id
href는 /read/id
내용은 title
key 값은 태그 추적 근거로 사용된다.