4. 컴포넌트 그외 (StyleSheet)

서창용·2022년 3월 2일
0
  1. StyleSheet로 스타일 입히기
import React from 'react';
import {View, StyleSheet} from 'react-native';

function Box() {
  return <View style={styles.box} />;
}

const styles = StyleSheet.create({
  box: {
    width: 64,
    heigth: 64,
    backgroundColor: 'black',
  },
});

export default Box;

자꾸 코딩 줄맞춤때문에 애러나서 빡쳐서 pretiier 끔

  • App.js 수정
import React from 'react';
import { SafeAreaView } from 'react-native';
import Box from './componets/Box';

const App = () => {
  return (
    <SafeAreaView>
      <Box />
    </SafeAreaView>
  );
};

export default App;

기본 포맷이나 안됨...자꾸 애러남...

크기 설정

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

function Box(props) {
  return (
    <View
      style={[styles.box, props.rounded && styles.rounded, sizes[props.size]]}
    />
  );
}

Box.defaultProps = {
  size: 'medium',
};

const styles = StyleSheet.create({
  box: {
    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;

App.js 수정

import React from 'react';
import {SafeAreaView} from 'react-native';
import Box from './componets/Box';

const App = () => {
  return (
    <SafeAreaView>
      <Box rounded={true} size="large" />
    </SafeAreaView>
  );
};

export default App;

size small,medium,large로 바꾸면 잘됨.

box.js props개체 구조 분해 할당하면 아래와 같음

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

function Box({rounded, size, color}) {
  return (
    <View
      style={[
        styles.box,
        rounded && styles.rounded,
        sizes[size],
        {
          backgroundColor: color,
        },
      ]}
    />
  );
}

Box.defaultProps = {
  size: 'medium',
  color: 'balck',
};

const styles = StyleSheet.create({
  box: {
    backgroundColor: 'yellow',
  },
  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;

잘됨

profile
관신분야 : 브랜딩, 마케팅, 파이썬, 리액트 네이티브, MSA, 엘라스틱서치

0개의 댓글