Sau khi cài đặt React Native, file App.js mặc định sẽ có sẵn cấu trúc cơ bản. Chúng ta sẽ sửa lại để hiển thị "Hello World".
Các bước thực hiện
1. Import các module cần thiết
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
2. Tạo component App
Dùng function component (hiện đại hơn class component):
const App = () => {
return (
Hello World
);
};
3. Định nghĩa style
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
text: {
color: 'green',
fontSize: 25,
fontWeight: 'bold',
},
});
4. Export component
export default App;
Mã hoàn chỉnh (App.js)
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
const App = () => {
return (
Hello World
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
text: {
color: 'green',
fontSize: 25,
fontWeight: 'bold',
},
});
export default App;
Chạy ứng dụng
# iOS npx react-native run-ios # Android npx react-native run-android
Kết quả
Màn hình trắng, chữ "Hello World" màu xanh lá, cỡ 25px, căn giữa cả ngang và dọc.
Giải thích các phần quan trọng
| Component | Vai trò |
|---|---|
View | Container gốc, tương đương <div> web. Hỗ trợ flexbox. |
Text | Hiển thị văn bản. Bắt buộc mọi text phải nằm trong Text. |
StyleSheet | Tạo stylesheet tối ưu hiệu suất (tách style ra khỏi render). |
flex: 1 | Chiếm toàn bộ không gian còn lại của parent. |
alignItems: 'center' | Căn giữa theo trục dọc (cross axis). |
justifyContent: 'center' | Căn giữa theo trục ngang (main axis). |
Lưu ý: React Native không dùng HTML tags (<div>, <span>, <p>). Luôn dùng View, Text, Image, v.v.