WEBKT

React Native 实现朋友圈多图上传预览删除功能的组件推荐

14 0 0 0

在 React Native 应用中实现类似微信朋友圈的多图上传功能,需要考虑用户体验、性能以及平台的兼容性。用户需要能够方便地选择多张图片,预览选中的图片,并在上传前可以删除不需要的图片。下面推荐几个在 React Native 中实现这个功能的常用组件,并分析它们的优缺点,提供代码示例。

1. react-native-image-picker

react-native-image-picker 是一个非常流行的 React Native 组件,用于从设备相册或相机中选择图片或视频。它提供了简单易用的 API,可以轻松集成到项目中。

  • 优点:

    • 跨平台支持:同时支持 iOS 和 Android。
    • 易于使用:API 简洁明了,容易上手。
    • 可定制性强:可以自定义 UI 和行为。
    • 支持图片和视频选择。
  • 缺点:

    • 依赖原生模块:需要配置原生依赖。
    • 可能存在兼容性问题:不同版本的 React Native 和原生依赖可能存在兼容性问题。

使用示例:

import { launchImageLibrary } from 'react-native-image-picker';
const selectImages = async () => {
const options = {
selectionLimit: 0, // Allow multiple image selection
mediaType: 'photo',
includeBase64: false,
};
launchImageLibrary(options, (response) => {
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.errorCode) {
console.log('ImagePicker Error: ', response.errorMessage);
} else {
const images = response.assets.map(asset => ({
uri: asset.uri,
type: asset.type,
name: asset.fileName,
}));
// Handle the selected images
console.log('selected images', images);
}
});
};

2. react-native-image-crop-picker

react-native-image-crop-picker 不仅可以从相册或相机中选择图片,还支持图片裁剪功能。如果你的应用需要用户裁剪图片,这个组件非常适合。

  • 优点:

    • 支持图片裁剪:允许用户在选择图片后进行裁剪。
    • 跨平台支持:同时支持 iOS 和 Android。
    • 可定制性强:可以自定义裁剪比例和 UI。
  • 缺点:

    • 依赖原生模块:需要配置原生依赖。
    • API 相对复杂:相比 react-native-image-picker,API 稍微复杂一些。

使用示例:

import ImageCropPicker from 'react-native-image-crop-picker';
const selectImages = async () => {
try {
const images = await ImageCropPicker.openPicker({
multiple: true,
mediaType: 'photo',
});
// Handle the selected images
console.log('selected images', images);
} catch (e) {
if (e.code === 'E_PICKER_CANCELLED') {
console.log('User cancelled image picker');
} else {
console.log('ImagePicker Error: ', e);
}
}
};

3. expo-image-picker

如果你正在使用 Expo 开发 React Native 应用,expo-image-picker 是一个不错的选择。它是由 Expo 团队维护的,与 Expo 平台集成良好。

  • 优点:

    • 与 Expo 集成:与 Expo 平台无缝集成,无需手动配置原生依赖。
    • 易于使用:API 简洁明了,容易上手。
    • 支持权限管理:方便管理相机和相册权限。
  • 缺点:

    • 仅适用于 Expo 应用:只能在 Expo 项目中使用。

使用示例:

import * as ImagePicker from 'expo-image-picker';
import { useState, useEffect } from 'react';
export default function App() {
const [images, setImages] = useState([]);
const [permissionInfo, requestPermission] = ImagePicker.useMediaLibraryPermissions();
useEffect(() => {
requestPermission();
}, []);
const pickImage = async () => {
if (!permissionInfo?.granted) {
return;
}
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsMultipleSelection: true,
aspect: [4, 3],
quality: 1,
});
if (!result.canceled) {
setImages(result.assets);
console.log(result.assets);
}
};
return (
<>
Pick an image from camera roll
);
}

实现图片预览和删除功能

无论你选择哪个图片选择组件,都需要自己实现图片预览和删除功能。这通常涉及到以下几个步骤:

  1. 存储选中的图片: 将用户选中的图片 URI 存储在一个状态变量中(例如,使用 useState hook)。
  2. 显示图片预览: 使用 FlatList 或其他列表组件来显示选中的图片。每个图片项使用 Image 组件来显示预览。
  3. 实现删除功能: 为每个图片项添加一个删除按钮。点击删除按钮时,从状态变量中移除对应的图片 URI,并更新列表。

示例代码(基于 react-native-image-picker):

import React, { useState } from 'react';
import { View, Image, TouchableOpacity, FlatList, StyleSheet } from 'react-native';
import { launchImageLibrary } from 'react-native-image-picker';
const ImageUploader = () => {
const [images, setImages] = useState([]);
const selectImages = async () => {
const options = {
selectionLimit: 0, // Allow multiple image selection
mediaType: 'photo',
includeBase64: false,
};
launchImageLibrary(options, (response) => {
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.errorCode) {
console.log('ImagePicker Error: ', response.errorMessage);
} else {
const newImages = response.assets.map(asset => ({
uri: asset.uri,
type: asset.type,
name: asset.fileName,
}));
setImages(prevImages => [...prevImages, ...newImages]);
}
});
};
const deleteImage = (uri) => {
setImages(prevImages => prevImages.filter(image => image.uri !== uri));
};
const renderItem = ({ item }) => (
<View style={styles.imageContainer}>
<Image source={{ uri: item.uri }} style={styles.image} />
<TouchableOpacity style={styles.deleteButton} onPress={() => deleteImage(item.uri)}>
Delete
</TouchableOpacity>
</View>
);
return (
<View>
<TouchableOpacity onPress={selectImages} style={styles.selectButton}>
Select Images
</TouchableOpacity>
<FlatList
data={images}
renderItem={renderItem}
keyExtractor={(item, index) => index.toString()}
numColumns={3}
/>
</View>
);
};
const styles = StyleSheet.create({
selectButton: {
backgroundColor: '#2196F3',
padding: 10,
borderRadius: 5,
margin: 10,
alignItems: 'center',
},
imageContainer: {
margin: 5,
width: 100,
height: 100,
},
image: {
width: '100%',
height: '100%',
resizeMode: 'cover',
},
deleteButton: {
backgroundColor: 'rgba(0, 0, 0, 0.5)',
position: 'absolute',
top: 0,
right: 0,
padding: 5,
color: 'white',
},
});
export default ImageUploader;

总结

选择哪个组件取决于你的具体需求和项目环境。如果你使用 Expo,expo-image-picker 是一个不错的选择。如果你需要图片裁剪功能,react-native-image-crop-picker 更适合。如果只是简单的图片选择,react-native-image-picker 足够满足需求。 无论选择哪个组件,都需要自己实现图片预览和删除功能。希望这些信息能帮助你实现类似微信朋友圈的多图上传功能。

码农小李 React Native图片上传多图选择

评论点评

打赏赞助
sponsor

感谢您的支持让我们更好的前行

分享

QRcode

https://www.webkt.com/article/10236