Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

내 공부 일지

컴포넌트간 합치기(컴포지션) 본문

study

컴포넌트간 합치기(컴포지션)

liujjang 2023. 12. 6. 17:28

컴포넌트를 그리다보니 css가 많이 중보 되는 현상이 있었다.

중복되는 것은 컨테이너의 border-radius와 box-shadow였다.

이 중복되는 스타일을 Card.js 컴포넌트 만들어 여기에 적용했다.

import React from 'react';
import './Card.css';
function Card(props) {
  return <div className='card'>{props.children}</div>;
}

export default Card;

 

하지만

<Card className='expenses'>
      <ExpenseItem title={props.items[0].title} amount={props.items[0].amount} date={props.items[0].date} />
      <ExpenseItem title={props.items[1].title} amount={props.items[1].amount} date={props.items[1].date} />
      <ExpenseItem title={props.items[2].title} amount={props.items[2].amount} date={props.items[2].date} />
      <ExpenseItem title={props.items[3].title} amount={props.items[3].amount} date={props.items[3].date} />
</Card>

위와 같이 className으로 스타일을 넣어줬던 것이 적용이 되지 않았다.

 

그렇다면 컴포넌트간 선택자를 어떻게 합칠까?

function Card(props) {
  const classes = ' card ' + props.className;
  return <div className={classes}>{props.children}</div>;
}

export default Card;

이렇게 변수를 만들어 props로 받은 선택자를 합성하면된다.

 

보통 카드와 같은 컨테이너를 사용할 때 컴포지션을 많이 사용한다.

'study' 카테고리의 다른 글

porps 더 간결하게 전달하기  (2) 2024.01.03
기본 css적용  (1) 2023.12.06
props란?  (1) 2023.12.05
new Date()  (0) 2023.12.01
컴포넌트의 이름은 대문자로!  (0) 2023.12.01