import React, { useState, useEffect } from 'react';
import { StyleSheet, View, Image, TouchableOpacity } from 'react-native';
import { CameraRoll } from 'react-native';
export default function CameraRollPicker({ onImagePicked }) {
const [image, setImage] = useState(null);
useEffect(() => {
getImageFromCameraRoll();
}, []);
const getImageFromCameraRoll = async () => {
// 从相册中获取最新的照片
const data = await CameraRoll.getPhotos({ first: 1 });
if (data && data.edges && data.edges.length > 0) {
const imageUri = data.edges[0].node.image.uri;
setImage({ uri: imageUri });
onImagePicked(imageUri);
}
};
return (
<View style={styles.container}>
<TouchableOpacity onPress={getImageFromCameraRoll}>
{image ? <Image style={styles.image} source={image} /> : <View style={styles.placeholder} />}
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
container: {
margin: 10,
alignItems: 'center',
},
image: {
width: 200,
height: 200,
borderRadius: 100,
resizeMode: 'cover',
},
placeholder: {
width: 200,
height: 200,
borderRadius: 100,
backgroundColor: 'lightgrey',
justifyContent: 'center',
alignItems: 'center',
},
});
这段代码使用React Native的CameraRoll API从设备的相册中获取最新的照片,并展示在一个可点击的图片占位符中。当点击占位符时,会再次调用getImageFromCameraRoll函数来更新显示的照片。这个例子简单直观地展示了如何在React Native应用中集成相册选择器的功能。