카테고리 없음
[React] Component Mapping
hyerm_2
2021. 8. 13. 10:57
반응형
SMALL
안녕하세요!
오늘은 이전 자바스크립트의 map() 메소드에 이어, React의 컴포넌트를 Mapping하는 방법에 대해 배워보도록 하겠습니다.
아래 사진과 같이 이름과 전화번호로 나눠져 있는 데이터들을 나타내는 예제로 살펴보겠습니다.
1. 가장 기본적인 코드
class App extends React.Component {
render(){
return (
<Contacts/>
);
}
}
class Contacts extends React.Component {
render(){
return(
<div>
<h1>Contacts</h1>
<ul>
<li>Abet 010-0000-0001</li>
<li>Betty 010-0000-0002</li>
<li>Chalie 010-0000-0003</li>
<li>David 010-0000-0003</li>
</ul>
</div>
);
}
}
=> 정말 가장 기본적인 코드죠?
Contact 클래스 내에 일일이 데이터들을 <li> 태그로 적어주었고, 그것을 App 클래스에서 call 하였습니다.
그럼 좀 더 나은 방법을 사용해볼까요?
2.
class ContactInfo extends React.Component {
render() {
return(
<li>{this.props.name} {this.props.phone}</li>
);
}
}
class Contacts extends React.Component {
render(){
return(
<div>
<h1>Contacts</h1>
<ul>
<ContactInfo name="Abet" phone="010-0000-0001"/>
<ContactInfo name="Betty" phone="010-0000-0002"/>
<ContactInfo name="Charlie" phone="010-0000-0003"/>
<ContactInfo name="David" phone="010-0000-0004"/>
</ul>
</div>
);
}
}
=> Contacts 클래스에서 ConatactInfo 클래스를 사용하였는데요.
ContactInfo는 this.props를 사용했고 name과 phone으로 두 데이터를 분리시켰습니다.
3. 이제 데이터를 mapping 해볼 차례 입니다!
import React from 'react';
class App extends React.Component {
render(){
return (
<Contacts/>
);
}
}
class Contacts extends React.Component {
constructor(props) {
super(props);
this.state = {
contactData: [
{name: "Abet", phone: "010-0000-0001"},
{name: "Betty", phone: "010-0000-0002"},
{name: "Charlie", phone: "010-0000-0003"},
{name: "David", phone: "010-0000-0004"}
]
};
}
render(){
return(
<div>
<h1>Contacts</h1>
<ul>
{this.state.contactData.map((contact, i) => {
return (<ContactInfo name={contact.name}
phone={contact.phone}
key={i}/>);
})}
</ul>
</div>
);
}
}
class ContactInfo extends React.Component {
render() {
return(
<li>{this.props.name} {this.props.phone}</li>
);
}
}
export default App;
=> Contacts 클래스에서, constructor를 통해 contactData들을 정의하였고 , return 부분에서 이 데이터들을 mapping 했는데요!
이때, ContactInfo 클래스를 이용하여 mapping 한 것을 볼 수 있습니다!
여기서 사용된 key는 child 컴포넌트에 독자성 (identity)을 부여한 것이라고 합니다!
참고자료
반응형
LIST