티스토리 뷰

 react-native를 공부한 지 얼마 지나지 않았지만, 벌써 마음에 든다. 

 

바로 css 파일을 굳이 따로 만들지 않는다는 것! 

 

개인적으로 css 파일을 따로 만들고 각종 셀렉터들을 막 찾아다니는 걸 정말 싫어해서... 이건 좀 반갑다.

 

간단하게 react-native에서 사용하는 StyleSheet의 특징과 예제 코드를 보자.


CSS와 StyleSheet의 차이점

- 셀렉터라는 개념이 존재하지 않는다.

- 모든 스타일 속성은 camelCase로 작성해야만 한다.

- display 속성은 기본적으로 flex이며, 다른 값은 none 밖에 없다.

- flexDirection 속성의 기본값은 웹에서는 row이지만, react-native 에서는 column이다.

- react-native에서 스타일링할 때 숫자 단위는 dp 뿐이다.

- background -> backgroundColor로 사용해야 한다.

- border 대신 borderWidth, borderStyle, borderColor 등을 따로따로 설정해야 한다.

 

예제 코드 1

import React from 'react';
import type {Node} from 'react';
import {SafeAreaView} from 'react-native';

import Box from './components/Box';

const App = () => (
  <SafeAreaView>
    <Box />
  </SafeAreaView>
);

export default App;

 

예제 코드 2

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

const Box = props => (
  <View style={[styles.box, props.rounded ? styles.rounded : null]} />
);

const styles = StyleSheet.create({
  box: {
    width: 64,
    height: 64,
    backgroundColor: 'black',
  },
  rounded: {
    borderRadius: 16,
  },
});

export default Box;

 

예제 코드 3

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

const Box = props => (
  <View
    style={[
      styles.box,
      props.rounded ? styles.rounded : null,
      sizes[props.size],
      {
        backgroundColor: props.color,
      },
    ]}
  />
);

const styles = StyleSheet.create({
  box: {
    width: 64,
    height: 64,
    backgroundColor: 'black',
  },
  rounded: {
    borderRadius: 16,
  },
  small: {
    width: 32,
    height: 32,
  },
  medium: {
    width: 64,
    height: 64,
  },
  large: {
    width: 128,
    height: 128,
  },
});

const sizes = {
  small: styles.small,
  medium: styles.medium,
  large: styles.large,
};

export default Box;
Comments