การจัดสไตล์แอปสามารถทำได้ 2 วิธี:
- ใช้คอมโพเนนท์ Stylesheet
- ใช้ Inline styles
ใช้คอมโพเนนท์ Stylesheet
คอมโพเนนท์ Stylesheet ของ React Native สะดวกและสะอาดตาเมื่อต้องการจัดสไตล์แอป เริ่มจากนำเข้า:
import { StyleSheet } from 'react-native';
สร้างสไตล์ด้วย Stylesheet:
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: StatusBar.currentHeight || 0,
},
item: {
margin: 10,
padding: 20,
marginVertical: 8,
marginHorizontal: 16,
}
});
ใช้สไตล์ในโค้ด:
ตัวอย่างใช้ Stylesheet กับ FlatList:
ตัวอย่าง 1
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,
}
});
ผลลัพธ์

ใช้ Inline styles
สามารถใช้พร็อพเพอร์ตี style เพื่อเพิ่มสไตล์ inline ได้ แต่ไม่ใช่ best practice เพราะอาจทำให้โค้ดอ่านยาก ตัวอย่างการใช้ inline style:
ตัวอย่าง 2
export default App;
import React from 'react';
import { Button, View, Alert } from 'react-native';
const App = () => {
return (
);
}
ผลลัพธ์
