: 구성. 여러 개의 component를 합쳐서 새로운 component를 만드는 것.
<사용 기법>
→ 어떻게 조합할 것인가???
: 상속. 다른 component들로부터 상속을 받아 새로운 component를 만드는 것이다. React에서는 주로 composition을 사용해 component들을 재사용하기 때문에 상속을 굳이 많이 사용하지는 않는다.
Example : 사용자 프로필 만들기 (주석 참고!!!!!)
<UserProfile.js>
import React from 'react';
//테두리 구현
function FancyBorder(props){
return (
// Object.assign: 스타일을 합칠 때 사용
<div style={Object.assign(props.style, {
display:'inline-block',
borderStyle: 'solid',
borderWidth: 2,
borderColor: '#80d900',
borderRadius: 16,
textAlign: 'center' })}>
<div style={{
padding: 8,
backgroundColor: '#80d900',
borderTopLeftRadius: 12,
borderTopRightRadius: 12 }}>
<span style={{ fontSize: 16, }}>
{props.title}
</span>
</div>
<div style={{ marginTop: 8 }}>
{/* containment */}
{props.children}
</div>
</div>
)
}
// 스타일을 하나의 객체로
const styles = {
imageContainer: {
width: 50,
margin: 'auto',
},
image: {
width: 50,
height: 50,
borderRadius: 25,
},
jobContainer: {
padding: 8,
},
jobText: {
fontSize: 16,
}
};
class UserProfile extends React.Component{
constructor(props){
super(props);
}
render(){
//props로 받은 정보를 user.--로 렌더링 할 수 있도록
const { user } = this.props;
return(
<FancyBorder
// specialization
title={user.name}
style={{width: 'calc(33.3% -12px)', margin: 4}}>
{/* containment */}
<div style={styles.imageContainer}>
<img
alt="profile"
src={user.image}
style={styles.image} />
</div>
<div style={styles.jobContainer}>
<span style={styles.jobText}>
{user.job}
</span>
</div>
</FancyBorder>
)
}
}
export default UserProfile;
<UserProfileList.js>
import React from 'react';
import UserProfile from './UserProfile';
class UserProfileList extends React.Component{
constructor(props){
super(props);
// user 정보 데이터
this.state={
users: [
{id: 1, name: 'Soyeon', image:'http://upload.wikimedia.org/wikipedia/commons/8/89/Portrait_Placeholder.png', job: 'Software Engineering'},
{id: 2, name: 'Leo', image:'http://upload.wikimedia.org/wikipedia/commons/8/89/Portrait_Placeholder.png', job: 'Software Engineering'},
{id: 3, name: 'Jack', image:'http://upload.wikimedia.org/wikipedia/commons/8/89/Portrait_Placeholder.png', job: 'Software Engineering'},
{id: 4, name: 'Tim', image:'http://upload.wikimedia.org/wikipedia/commons/8/89/Portrait_Placeholder.png', job: 'Software Engineering'},
{id: 5, name: 'Amy', image:'http://upload.wikimedia.org/wikipedia/commons/8/89/Portrait_Placeholder.png', job: 'Software Engineering'},
{id: 6, name: 'Lee', image:'http://upload.wikimedia.org/wikipedia/commons/8/89/Portrait_Placeholder.png', job: 'Software Engineering'},
]
}
}
render(){
const { users } = this.state;
// UserProfile 렌더링
return(
<div>
{users.map((user) => {
return(
<UserProfile
// prop으로 user를 넣어줌
user={user} />
)
})}
</div>
)
}
}
export default UserProfileList;