본문 바로가기
Frontend/React Native

[React Native] 리액트 네이티브 styleSheet로 스타일 적용하기

by couque 2023. 3. 30.
반응형

웹 환경에서 스타일을 적용하기 위해 사용하는 css처럼 리액트 네이티브에서는 styleSheet를 사용한다.

 

CSS와 styleSheet의 차이점은

  • css에서 사용하는 셀렉터가 존재하지 않는다.
  • 스타일 속성을 작성할때는 camelCase로 작성한다.
  • display 속성은 flex, none으로 구성되어 있다.
  • flexDirection 속성은 column.
  • 스타일 단위는 dp만 사용할 수 있다.
  • css에서 background는 리액트 네이티브에서는 backgroundColor로 사용한다.
  • css에서 border는 borderWidth, borderStyle, borderColor등으로 설정한다.

styleSheet를 사용하는 방법을 아래 예제로 알아보자.

styleSheet는 js파일마다 설정할 수 있고, styleSheet를 생성하여 담는 변수명을 다르게 하여 한 파일에서 여러개를 만들수도 있을것이다.

const styles = StyleSheet.create({
    view: {
        flex: 3,
        alignItems: "flex-end",
        flexDirection: "column",
        alignSelf: "center",
        padding: 10,
    },
    title: {
      fontSize: 18,
      fontWeight: "bold",
      marginBottom: 10,
      alignSelf: "flex-start",
    },
    date: {
      fontSize: 16,
      color: "#787774",
      borderRadius: 30,
      padding:3,
    },
    price: {
      flexDirection: "row",
      justifyContent: "space-between",
      alignItems: "center",
      width: "100%",
    },
 });

 

위와 같이, styleSheet를 정의했다면 styleSheet를 태그에 아래와 같이 적용하면 된다.

<View style={styles.view}>
    <Text style={styles.title}>TITLE</Text>
    <View style={styles.price}>
      <Text style={styles.date}>2023. 01. 01</Text>
    </View>
</View>

 

참고로 styleSheet를 사용하기 위해서는 상단에 styleSheet를 import 해줘야 한다.

 import {View, Text, StyleSheet} from 'react-native';

 

react native의 컴포넌트를 사용하기 위해서는 해당 컴포넌트를 위와 같이 import를 해서 사용하면 된다.

반응형

댓글