본문 바로가기
개발 공부 일지/React

리액트 - [Styled Component] 상속/CSS 함수

by yelimu 2024. 8. 12.

상속

 

styled(Component) 함수  -> Component의 스타일 상속받음

* Component 가 styled.tagname으로 만든 컴포넌트일때 사용

(styled component는 내부적으로 className을 생성하고 자체적으로 생성된 클래스네임에 styled() 함수의 스타일이 입혀지는것)

import styled from 'styled-components';
import Button from './Button';

const SubmitButton = styled(Button)`
  background-color: #de117d;
  display: block;
  margin: 0 auto;
  width: 200px;

  &:hover {
    background-color: #f5070f;
  }
`;

function App() {
  return (
    <div>
      <SubmitButton>계속하기</SubmitButton>
    </div>
  );
}

export default App;

JSX로 만든 컴포넌트는?

className값을 Prop으로 따로 내려줘야 한다. --> 그러고나서 styled(component) 적용

 

function TermsOfService({ className }) {
  return (
    <div className={className}>
      ...
    </div>
  );
}

import styled from 'styled-components';
import Button from './Button';
import TermsOfService from './TermsOfService';

const StyledTermsOfService = styled(TermsOfService)`
  background-color: #ededed;
  border-radius: 8px;
  padding: 16px;
  margin: 40px auto;
  width: 400px;
`;

const SubmitButton = styled(Button)`
  background-color: #de117d;
  display: block;
  margin: 0 auto;
  width: 200px;

  &:hover {
    background-color: #f5070f;
  }
`;

function App() {
  return (
    <div>
      <StyledTermsOfService />
      <SubmitButton>계속하기</SubmitButton>
    </div>
  );
}

export default App;

css 함수 사용하기 

Button과 Input에 동일한 fontsize를 적용하려고 할때 ~ 

import styled, { css } from 'styled-components';

const SIZES = {
  large: 24,
  medium: 20,
  small: 16
};

const fontSize = css`
  font-size: ${({ size }) => SIZES[size] ?? SIZES['medium']}px;
`;

const Button = styled.button`
  ...
  ${fontSize}
`;

const Input = styled.input`
  ...
  ${fontSize}
`;