用 React native 写一个拍照上传多张图片的组件
时间: 2023-12-05 22:04:35 浏览: 46
以下是一个简单的 React Native 组件,可以实现拍照上传多张图片的功能:
```javascript
import React, { useState } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, Image, ScrollView } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import Constants from 'expo-constants';
const ImagePickerComponent = () => {
const [selectedImages, setSelectedImages] = useState([]);
const pickImage = async () => {
let result = await ImagePicker.launchCameraAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
if (!result.cancelled) {
setSelectedImages([...selectedImages, { uri: result.uri }]);
}
};
return (
<View style={styles.container}>
<TouchableOpacity style={styles.button} onPress={pickImage}>
<Text style={styles.buttonText}>Take a photo</Text>
</TouchableOpacity>
<ScrollView horizontal={true}>
{selectedImages.map((image, index) => (
<View key={index}>
<Image source={{ uri: image.uri }} style={styles.image} />
</View>
))}
</ScrollView>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
},
button: {
alignItems: 'center',
backgroundColor: '#DDDDDD',
padding: 10,
marginBottom: 10,
},
buttonText: {
fontSize: 20,
},
image: {
width: 100,
height: 100,
margin: 5,
},
});
export default ImagePickerComponent;
```
这个组件使用了 `expo-image-picker` 库来打开相机拍照,并将拍摄的图片加入到一个数组中。这个数组中的每一个元素都是一个对象,包含了图片的 URI。然后,使用 `ScrollView` 组件将所有的图片展示出来。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)