react native基于expo上传图片组件expo-image-picker的使用
import React, { useState } from 'react';
import { StyleSheet, Button, View, Image, Text } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
export default function App() {
const [image, setImage]�] = useState(null);
const pickImage = async () => {
// 选择图片
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
if (!result.cancelled) {
setImage(result.uri);
}
};
return (
<View style={styles.container}>
<Button title="选择图片" onPress={pickImage} />
{image && <Image source={{ uri: image }} style={styles.image} />}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
image: {
width: 200,
height: 200,
marginTop: 20,
},
});
这段代码展示了如何在React Native应用中使用expo-image-picker来选择并显示图片的基本用法。通过一个按钮触发pickImage
函数,该函数调用ImagePicker.launchImageLibraryAsync
来打开图片库,用户选择图片后,图片的URI被存储在状态image
中,并且通过Image
组件显示出来。
评论已关闭