Framework/React & RN
React Native/Typescript 환경에서 Styled-component를 사용하는 방법
Joonfluence
2022. 4. 1. 19:54
서론
대상독자
RN 개발 시, Styled-component를 사용하고 싶은 개발자
학습목표
오늘은 RN Expo와 타입스크립트 환경에서 Styled-component를 설정하는 방법에 대해서 알아보겠습니다.
본론
라이브러리 설치하기
yarn add styled-components;
yarn add -D @types/styled-components @types/styled-components-react-native
리액트에서 사용할 때와 유일한 차이점은 @types/styled-components-react-native
패키지를 추가로 설치해준다는 점입니다.
실제로 사용해보기
테스트를 위해 버튼 컴포넌트를 스타일드 컴포넌트를 활용하여, 스타일링 해보도록 하겠습니다. 잘 적용되는 것을 보실 수 있을 겁니다.
import React, { FC } from "react";
import { TouchableOpacity, TouchableOpacityProps } from "react-native";
import styled from "styled-components/native";
import Typography from "components/Shared/Typography";
export type Props = {
label: string;
color?: string;
onPress?: (data?: any) => void;
} & TouchableOpacityProps;
const Component: FC<Props> = ({ label, onPress, color, ...rest }) => {
return (
<StyledButton label="" onPress={onPress} color={color} {...rest}>
<StyledText>{label}</StyledText>
</StyledButton>
);
};
export default Component;
const StyledButton = styled(TouchableOpacity)<Props>`
width: 100%;
align-items: center;
justify-content: center;
height: 50px;
background-color: ${({ color }) =>
color ? color : 'red'};
`;
const StyledText = styled.Text`
color: white;
`;
마무리
설치만으로 아주 간단하게 설정을 끝낼 수 있습니다.
반응형