styled-component [React]

특이점사람·2022년 5월 17일
2

react

목록 보기
1/3

무엇인가?

구성 요소에 반응하는 스타일을 제공하는 CSS in JS 스타일링을 위한 프레임워크 입니다. 자바스크립트의 태그가 지정된 템프릿 리터럴과 CSS 기능을 사용합니다. 이외에도 CSS in JS 라이브러리로는 JSSemotion이 존재합니다.

왜 사용하는가?

  1. Global namespace
  2. Dependencies
  3. Dead Code Elimination
  4. Minification
  5. Sharing Constants
  6. Non-deterministic Resolution
  7. Isolation

위에 언급된 CSS의 문제점을 해결하기 위해서 사용합니다. 그외에 styled-componets를 사용해야 하는 이유는 아래와 같습니다.

자유로운 CSS 커스텀 컴포넌트

인라인 스타일링

모바일 지원

스타일 스코프

No-class policy

서버 사이드 렌더링

CSS 테스팅

Sass와 세련된 지원

어떻게 사용하는가?

import React from 'react';
import {Button} from '@ant-design/react-native';
import styled, {css} from 'styled-components/native';

const ExamStyledComponent = () => {
  const [text, onChangeText1] = React.useState('');

  return (
    <>
      <StyledText length={text.length}>StyledView Components</StyledText>
      <StyledButton type="primary"> test Button </StyledButton>
      <StyledTextInput onChangeText={onChangeText1} value={text} />
      <StyledTextInput inputColor="blue" bold />
    </>);
};

interface StyledTextProps {
  readonly length?: number;
}

const StyledText = styled.Text<StyledTextProps>`
  padding: 50px;
  background-color: yellow;
  text-align: center;
`;

//라이브러리에서 제공된 UI 컴포넌트 활용
const StyledButton = styled(Button)`
  margin: 30px;
  background-color: blue;
`;

interface StyledTextInputProps {
  readonly inputColor?: string;
  readonly bold?: boolean;
}

const StyledTextInput = styled.TextInput<StyledTextInputProps>`
  padding: 20px;
  margin: 10px;
  color: ${props => props.inputColor || 'palevioletred'};
  background: papayawhip;
  border: none;
  border-radius: 3px;
  ${props =>
    props.bold &&
    css`
      // props 를 쓰지 않는다면 사실 굳이 css 로 감쌀 필요는 없음
      background: #523123;
      border: solid 2px;
    `}
`;

export default ExamStyledComponent;

참고

https://styled-components.com/docs/basics

https://tech.devsisters.com/posts/react-extend-theme/

https://velog.io/@ikaret/React-Native-에서-Styled-Component-사용하기

https://analogcoding.tistory.com/181

https://dev-yakuza.posstree.com/ko/react-native/styled-components/

profile
안녕하세요.

0개의 댓글