Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

React Native에서 앱에 스타일(CSS)을 적용하는 방법 완벽 가이드

React Native에서 앱의 UI를 꾸미기 위한 스타일 적용 방법은 크게 두 가지로 나눌 수 있습니다.

  • StyleSheet 컴포넌트 사용
  • 인라인(Inline) 스타일 사용

1. StyleSheet 컴포넌트 사용하기

React Native의 StyleSheet 컴포넌트는 앱에 스타일을 적용할 때 가장 깔끔하고 효율적인 방법입니다. 스타일을 한 곳에서 체계적으로 관리할 수 있어 코드 가독성이 높아지며, 렌더링 성능 측면에서도 유리합니다. StyleSheet를 사용하려면 먼저 아래와 같이 react-native 모듈에서 임포트해야 합니다.

import { StyleSheet } from 'react-native';

그다음 StyleSheet.create() 메서드를 사용해 다음과 같이 스타일 객체를 정의합니다.

const styles = StyleSheet.create({
    container: {
        flex: 1,
        marginTop: StatusBar.currentHeight || 0,
    },
    item: {
        margin: 10,
        padding: 20,
        marginVertical: 8,
        marginHorizontal: 16,
    }
});

생성한 스타일은 아래와 같이 컴포넌트의 style 속성에 전달하여 적용합니다.

<View style={styles.container}></View>

다음은 StyleSheet를 활용해 FlatList 컴포넌트를 화면에 표시하는 실전 예제입니다.

예제 1 – FlatList와 StyleSheet 함께 사용하기

import React from "react";
import { FlatList , Text, View, StyleSheet, StatusBar } from "react-native";
export default class App extends React.Component {
    constructor() {
        super();
        this.state = {
            data: [
                { name: "Javascript Frameworks", isTitle: true },
                { name: "Angular", isTitle: false },
                { name: "ReactJS", isTitle: false },
                { name: "VueJS", isTitle: false },
                { name: "ReactNative", isTitle: false },
                { name: "PHP Frameworks", isTitle: true },
                { name: "Laravel", isTitle: false },
                { name: "CodeIgniter", isTitle: false },
                { name: "CakePHP", isTitle: false },
                { name: "Symfony", isTitle: false }
            ],
            stickyHeaderIndices: []
        };
    }
    renderItem = ({ item }) => {
        return (
            <View style={styles.item}>
                <Text style={{ fontWeight: (item.isTitle) ? "bold" : "", color: (item.isTitle) ? "red" : "gray"}} >
                    {item.name}
                </Text>
            </View>
        );
    };
    render() {
        return (
            <View style={styles.container}>
                <FlatList
                    data={this.state.data}
                    renderItem={this.renderItem}
                    keyExtractor={item => item.name}
                    stickyHeaderIndices={this.state.stickyHeaderIndices}
                />
            </View>
        );
    }
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        marginTop: StatusBar.currentHeight || 0,
    },
    item: {
        margin: 10,
        padding: 20,
        marginVertical: 8,
        marginHorizontal: 16,
    }
});

실행 결과

React Native에서 앱에 스타일(CSS)을 적용하는 방법 완벽 가이드

2. 인라인 스타일 사용하기

컴포넌트의 style 속성에 스타일 객체를 직접 작성하면 별도의 StyleSheet 없이 인라인 방식으로 스타일을 지정할 수 있습니다. 다만 코드가 길어질수록 가독성이 떨어지기 때문에, 간단한 스타일링에만 사용하는 것이 바람직합니다. 아래는 React Native 컴포넌트 내부에서 인라인 스타일을 적용한 실제 동작 예제입니다.

예제 2 – 버튼에 인라인 스타일 적용하기

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

const App = () => {
    return (
        <View style={{flex :1, justifyContent: 'center', margin: 15 }}>
            <Button
                title="Click Me"
                color="#9C27B0"
                onPress={() => Alert.alert('Testing Button for React Native ')}
            />
        </View>
    );
}

export default App;

실행 결과

React Native에서 앱에 스타일(CSS)을 적용하는 방법 완벽 가이드