如果你指的是 React Native 的 View、Text、Image、ScrollView(而不是 React Web),下面是开发中最常用的组件及注意事项,可以作为面试或日常开发速查。
1. View
View 相当于 HTML 中的 div,是最基础的布局容器。
常用属性
<View
style={styles.container}
pointerEvents="none"
>
</View>
常见 props
-
style
-
onLayout
-
pointerEvents
-
accessible
注意事项
① 默认是 Flex 布局
React Native 默认:
flexDirection: 'column'
不是 Web 的
display:flex;
flex-direction:row;
例如:
<View style={{
flex:1,
justifyContent:'center',
alignItems:'center'
}}>
② 没有 margin:auto
Web:
margin:auto;
RN:
alignSelf:'center'
或者
justifyContent
alignItems
③ View 不能显示文本
错误:
<View>
Hello
</View>
正确:
<View>
<Text>Hello</Text>
</View>
④ View 支持嵌套
<View>
<View/>
<View/>
</View>
没有问题。
2. Text
所有文字都必须放到 Text 中。
常用属性
<Text
numberOfLines={2}
ellipsizeMode="tail"
selectable
>
注意事项
① 所有字符串必须放在 Text 中
错误:
<View>
abc
</View>
正确:
<View>
<Text>abc</Text>
</View>
② Text 可以嵌套
<Text>
Hello
<Text style={{color:'red'}}>
World
</Text>
</Text>
输出:
Hello World
③ numberOfLines
限制行数
<Text numberOfLines={1}>
超出:
...
④ selectable
允许复制
<Text selectable>
⑤ onPress
Text 可以直接点击
<Text onPress={handleClick}>
不用一定包 Button。
3. Image
用于显示图片。
支持:
-
网络图片
-
本地图片
-
Base64
本地图片
<Image source={require('./logo.png')} />
注意:
必须使用 require
不能:
<Image source="./logo.png"/>
网络图片
<Image
source={{
uri:'https://example.com/a.png'
}}
/>
必须指定宽高
错误:
<Image
source={{uri:'...'}}
/>
可能完全不显示。
正确:
<Image
style={{
width:100,
height:100
}}
/>
resizeMode
类似 CSS object-fit。
resizeMode="cover"
常见:
cover
contain
stretch
center
repeat
默认不会缓存所有网络图片
如果大量图片:
通常使用
react-native-fast-image
提高缓存性能。
图片圆角
style={{
width:80,
height:80,
borderRadius:40
}}
4. ScrollView
用于滚动内容。
<ScrollView>
注意事项
① 适合少量数据
因为:
一次性全部渲染
例如:
20
50
100
没问题。
如果:
1000
5000
10000
不要使用。
应该:
FlatList
SectionList
② ScrollView 必须有高度
例如:
<View style={{flex:1}}>
<ScrollView>
或者:
height:300
否则:
不能滚动。
③ contentContainerStyle
很多人容易写错。
错误:
style={{
justifyContent:'center'
}}
应该:
contentContainerStyle={{
justifyContent:'center'
}}
区别:
style:
控制 ScrollView 本身。
contentContainerStyle:
控制里面内容。
④ 横向滚动
<ScrollView horizontal>
⑤ 去掉滚动条
showsVerticalScrollIndicator={false}
横向:
showsHorizontalScrollIndicator={false}
⑥ 下拉刷新
<ScrollView
refreshControl={
<RefreshControl
refreshing={loading}
onRefresh={loadData}
/>
}
/>
⑦ 键盘遮挡
输入框页面:
可以使用
KeyboardAvoidingView
或者
keyboardShouldPersistTaps="handled"
避免点击输入框时滚动冲突。
什么时候用 ScrollView,什么时候用 FlatList?
| 场景 | 推荐组件 | 原因 |
|---|---|---|
| 少量固定内容 | ScrollView | 简单、易用 |
| 表单页面 | ScrollView | 内容较少且需要整体滚动 |
| 新闻列表 | FlatList | 按需渲染,性能好 |
| 聊天列表 | FlatList | 支持虚拟列表,适合大量数据 |
| 商品列表 | FlatList | 节省内存,滚动流畅 |
| 分组列表 | SectionList | 支持分组与吸顶 |
开发中的最佳实践
-
View
-
用于布局,不直接放字符串。
-
善用
flex、justifyContent、alignItems实现布局。
-
-
Text
-
所有文本都放在
Text中。 -
长文本使用
numberOfLines与ellipsizeMode控制显示。 -
需要点击时可直接使用
onPress。
-
-
Image
-
始终设置
width和height。 -
本地图片使用
require(),网络图片使用{ uri: ... }。 -
使用
resizeMode控制图片适配方式。
-
-
ScrollView
-
仅适用于内容较少的页面。
-
内容很多时优先使用
FlatList或SectionList。 -
区分
style(容器样式)与contentContainerStyle(内容样式),避免布局问题。
-
掌握这些注意事项,可以覆盖 React Native 日常开发中绝大多数基础 UI 场景。