Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách thêm styling/CSS vào ứng dụng React Native


Styling ứng dụng có thể thực hiện bằng hai cách:

  • Dùng component StyleSheet
  • Dùng Inline styles

Dùng StyleSheet component

StyleSheet của React Native rất tiện lợi và gọn gàng. Import như sau:

import { StyleSheet } from 'react-native';

Tạo style:

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

Sử dụng trong code:

Ví dụ 1: StyleSheet với FlatList

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 (
            
                
                    {item.name}
                
            
        );
    };
    render() {
        return (
            
                 item.name}
                    stickyHeaderIndices={this.state.stickyHeaderIndices}
                />
            
        );
    }
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        marginTop: StatusBar.currentHeight || 0,
    },
    item: {
        margin: 10,
        padding: 20,
        marginVertical: 8,
        marginHorizontal: 16,
    }
});

Kết quả

Cách thêm styling/CSS vào ứng dụng React Native

Dùng Inline styles

Dùng prop style trực tiếp. Không khuyến khích vì khó đọc code. Ví dụ:

Ví dụ 2

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

const App = () => {
    return (
        
            

Kết quả

Cách thêm styling/CSS vào ứng dụng React Native