【第2篇】组件和样式指南:像拼乐高一样构建界面
🎯 技术专家视角导语
“用 View、Text 拼起来就是 App?”
“对,就像拼乐高一样,你掌握了组件,React Native 的世界就为你展开。”
🧱 React Native 的组件系统
🔹 内置组件
View:所有布局的容器Text:文字展示的核心组件Image:加载本地或网络图片ScrollView:可滚动容器
🔹 自定义组件
通过函数/类组合多个组件,形成具有特定功能的“积木模块”。
const Card = ({ title }) => (
<View style={styles.card}>
<Text style={styles.title}>{title}</Text>
</View>
)
🔹 常用第三方组件库
react-native-vector-icons:图标库react-native-paper:Material Design UIreact-native-gesture-handler:手势识别
🎨 样式系统:像写 CSS,但更 JS
| 特性 | React Native 样式说明 |
|---|---|
| 样式写法 | JS 对象(非 CSS 语法) |
| 属性 | 类似 CSS:fontSize、color 等 |
| Flex 布局默认方向 | flexDirection: 'column'(和网页相反) |
| 没有 px 单位 | 直接写数字:fontSize: 16 即表示 16px |
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
justifyContent: 'center',
alignItems: 'center'
},
title: {
fontSize: 24,
color: '#333'
}
})
✍️ 小试牛刀:组件 + 样式 Demo
import { View, Text, StyleSheet } from 'react-native'
export default function App() {
return (
<View style={styles.container}>
<Text style={styles.text}>Hello, React Native!</Text>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F0F0F0',
justifyContent: 'center',
alignItems: 'center'
},
text: {
color: '#1e90ff',
fontSize: 20
}
})
🧩 总结:组件 + 样式是你掌握生产力的第一步
- 🧠 拆解复杂 UI 为小组件,提升复用性
- 💡 使用 Flex 布局处理自适应屏幕
- 🛠 合理封装样式,避免硬编码
📘 下一篇预告:
👉 《状态管理实战:从 useState 到 Redux,一步步解锁“神经系统”》